How to Hide Warnings in PHP

Ugh! As PHP developers, we’ve all seen something like this more than we’d like:

Warning: include(included.php): failed to open stream: No such file or directory in /var/www/html/include1.php on line 6

As a general rule, you don’t want to hide warnings like this. You want to be aware of them, and fix them, before your users see them. If you want to handle warnings in another way, I’ll talk about that below. But first, let’s look at the standard, “best practices” way to deal with them.

In your development environment, you want PHP warnings to be displayed and logged. In production, you want them hidden, but logged.

In order to accomplish this, open your php.ini file in your editor of choice, and search for display_errors. Change the setting to On for development, and Off for production. Like this:

display_errors = On

or

display_errors = Off

You may also want to check that errors are being logged as desired in both environments, like this (also in php.ini):

log_errors = On

Also, make sure that your error_reporting setting is sensible. If you look in php.ini, you’ll find that the recommended settings for error_reporting are:

error_reporting = E_ALL
;   Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
;   Development Value: E_ALL
;   Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT

After making changes to php.ini, usually you will need to restart Apache in order for the changes to take effect.

If you don’t see the change taking place, you should double check a few things:

  • Make sure there are no duplicate occurrences of display_errors in your ini file.
  • Look around to see if there are any other php.ini files with this setting that might be overriding the main one.
  • Check that the code is not using ini_set to override the php.ini file.

Now, sometimes a warning is expected, and you just want the warning logged, and not displayed. In that case, you can write your code to work around the warning, like so:

$display_errors = ini_get('display_errors'); // get the initial value
ini_set('display_errors', 0); // do not display errors or warnings. Yup, it turns off warnings, too.
$result = function_that_causes_a_warning(); // the warning will not be displayed because of the above line.
ini_set('display_errors', $display_errors); // reset display_errors to the initial value.

This use case is very unusual. If you find yourself needing to do this, ask yourself if it’s really the best thing to do. Normally, you don’t want to “hack” the global settings that have been applied in php.ini.

If you found this interesting, click the subscribe button below! I write a new post about once a week.

Leave a Reply

Your email address will not be published. Required fields are marked *