One of the features of PHP is its comprehensive error-handling functionality. You can control many aspects of how errors are triggered and handled. In this article I will cover the key aspects of errors and error handling in PHP.
Types of Errors:
There are a number of different error types that may be triggered in PHP. Some of these can be recovered from, while others cannot (that is, some errors will cause the current script execution to immediately halt).
The following list is from the PHP manual entry on Error Predefined Constants.
E_ERROR: Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted
E_WARNING: Run-time warnings (non-fatal errors). Execution of the script is not halted
E_PARSE: Compile-time parse errors. Parse errors should only be generated by the parser.
E_CORE_ERROR: Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP.
E_CORE_WARNING: Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP.
E_COMPILE_ERROR: Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine
E_COMPILE_WARNING: Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine
E_USER_ERROR: User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error()
E_USER_WARNING: User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error()
E_USER_NOTICE: User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error()
E_STRICT: Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code
E_RECOVERABLE_ERROR: Catchable fatal error. It indicates that a probably dangerous error occured, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR
E_DEPRECATED: Run-time notices. Enable this to receive warnings about code that will not work in future versions
E_USER_DEPRECATED: User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error()
When you want to refer to all error levels easily (as I will show you later in the article), you can use E_ALL. This includes all errors and warnings, except for E_STRICT.
Which Errors Are Reported?
When one of the above errors occurs, whether or not it is reported is determined by the error_reporting setting
.
You can set this either in php.ini
You can set it in your web server configuration (such as in httpd.conf
or a .htaccess
file)
You can set it at runtime (that is, from within your PHP script)
If you set it in your php.ini
you can combine the above error constants into a bitwise mask. The following listing shows two examples that can be used in php.ini.
Listing 1 listing-1.txt
error_reporting = E_ALL & ~E_NOTICE ; all errors and not notices
error_reporting = E_WARNING | E_NOTICE ; warnings or notices
If you set the error level in httpd.conf
or in .htaccess
, these constant names do not exist. You must use their corresponding integer values instead.
The following shows a sample .htaccess
file:
Listing 2 listing-2.txt
# this sets E_ALL & ~E_NOTICE - E_ALL is 30719 in PHP 5.3, 6143 in PHP 5.2
php_value error_reporting 30711
# this sets E_WARNING | E_NOTICE (2 | 8)
php_value error_reporting 10
To set at runtime you can use either ini_set()
or error_reporting().
Listing 3 listing-3.php
<?php
ini_set('error_reporting', E_ALL & ~E_NOTICE);
error_reporting(E_WARNING | E_NOTICE);
?>
Another useful trick is to temporarily set a new error level, then revert back to the old one once you're done. This can be useful if you want to report on deprecated features normally, but a third-party library you're using would cause a bunch of warnings otherwise.
When you call error_reporting()
, the current setting is returned. You can store this value temporarily.
Listing 4 listing-4.php
<?php
// retrieve original reporting level then disable error reporting
$oldLevel = error_reporting(0);
// do something that might cause notices or warnings
// all done: restore old level
error_reporting($oldLevel);
?>
Using a Custom Error Handler:
As previously mentioned, PHP will either write errors to output or a log file, or both. You can instead use a custom error handler, which bypasses both of these mechanisms completely.
*Important: In fact, you must return true from the callback, otherwise the standard PHP error handler will be called afterwards.*
This is achieved using the set_error_handler()
function. This function accepts a PHP callback
as its first argument. This callback accepts up to 5 arguments:
1. $errno (integer): The level of the error raised (e.g. E_WARNING)
2. $errstr (string) : The error message describing the error
3. $errfile (string, optional) : The filename the error was raised in
4. $errline (integer, optional) : The line number in the file the error was raised
5. $errcontext (array, optional) : An array that points to the active symbol table
The following code demonstrates a basic error handler. Since all error messages are passed to the handler despite the error reporting setting, it can be honored as shown in the first line of the errorHandler function.
Listing listing-9.php
<?php
function errorHandler($errno, $errstr, $errfile, $errline, $errcontext)
{
// use bitwise operators to check the error reporting setting
if (error_reporting() & $errno == 0) {
// we're not to report on this message
return;
}
// check the type of error so it can be handled accordingly
switch ($errno) {
case E_USER_ERROR:
echo sprintf(
'User Error: %s (file %s, line %d)',
$errstr,
$errfile,
$errline
);
break;
case E_USER_WARNING:
// output a message
break;
// handle other error numbers accordingly
}
// return true so standard error handler is bypassed
return true;
}
// tell PHP to use the error handler
set_error_handler('errorHandler');
// trigger a fake error just to demonstrate the callback
trigger_error('Fake error', E_USER_ERROR);
?>
If you want to script to finish execution when a certain error occurs, you must manually exit (by calling exit() or die()) from your error handler.
*One final note: Not all types of errors can be dealt with using a custom error handler. From the PHP manual:*
“The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING,
and most of E_STRICT raised in the file where set_error_handler() is called.”