PHP error reporting

Error levels

name value description example 1 example 2 E_ERROR 1 Fatal run-time errors notdefined(); E_WARNING 2 Run-time warnings 1 / 0; E_PARSE 4 Compile-time parse errors +-; E_eval(‘+-;’); E_NOTICE 8 Run-time notices print $i_am_not_defined; E_CORE_* varies generated by PHP core E_USER_* varies generated by trigger_error E_ALL 2047 Everything

Custom Error Handler

It can only catch E_WARNING, E_PARSE, E_USER_ERROR, E_USER_WARNING and E_USER_NOTICE. If something else happens, PHP’s default error handler takes place.

functional my_error_handler($errno, $error, $file, $line) {  ... handle the error ...}

set_error_handler(‘my_error_handler’);

Apache

In Apache, you can customize how it responses to a particular HTTP status code. It can show a message or load a specific page. e.g. (from Apache’s doc)

ErrorDocument 500 /cgi-bin/crash-recoverErrorDocument 500 "Sorry, our script crashed. Oh dearErrorDocument 500 http://xxx/ErrorDocument 404 /Lame_excuses/not_found.htmlErrorDocument 401 /Subscription/how_to_subscribe.html

However, when executed as an Apache module PHP returns a HTTP status code of 200 (OK) even if there is an compile or run-time error. (Not sure if it’s a bug or a feature, since this behavior is not mentioned anywhere else.) Therefore, one cannot use Apache’s custom error capability for PHP errors.

Instead, either use a custom error handler (see above) or have PHP wrap the message inside some specific HTML code (see below).

Pretty-printing Error Messages

Config keys error_prepend_string and error_append_string are used to determine the HTML code that prepends or appends an error message.

e.g. To display each error message inside a box, put these in php.ini:

; String to output before an error message.error_prepend_string = "<fieldset>An error has occured. Please notify the <a href=\"mailto:admin@yourname.com\">administrator</a> with the following error message: <br>"; String to output after an error message.error_append_string = "</fieldset>"

To make the change effective to a directory instead of system-wide, put these in .htaccess:

php_value error_prepend_string "(... starting tags ...)"php_value error_append_string "(... ending tags ...)"

Note: Because any compile-time error stops the compilation, there will be at most one box.