Every PHP developer, system administrator and webmaster knows that the best way to debug PHP scripts is to show and/or log its errors by settings the appropriate values to the error_reporting, display_errors and log_errors directives in the PHP.INI file.
Here’s a typical scenario for a production web server:
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
log_errors = On
- The first command instructs PHP to take into consideration all kind of warnings minus the DEPRECATED and STRICT ones: the DEPRECATED warnings are related to code that might cease to work in future versions, while the STRICT ones are about code that could cause interoperability or forward compatibility issues.
- The second command prevents PHP from showing the error to the end-user, which is something we almost always want to avoid in production scenarios.
- The third command tells PHP to log the errors to secure locations such as STDERR or a local file which has to be specified by an additional error_log directive.
What if we want to override these settings programmatically? For example, change the default behaviour within a single page or a group of pages?
Luckily enough, we can do this by using the ini_set() function, which allows to change most configuration directives programmatically.
Here’s the required code:
ini_set('error_reporting', E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE); // Show all errors minus STRICT, DEPRECATED and NOTICES
ini_set('display_errors', 0); // disable error display
ini_set('log_errors', 0); // disable error logging
That’s about it: it’s worth noting that this will work on either PHP 5.x and PHP 7.x.