You want to create a custom error handler that lets you control how PHP reports errors.
To set up your own error function, use set_error_handler():
1 2 3 4 5 6 |
set_error_handler('pc_error_handler'); function pc_error_handler($errno, $error, $file, $line) { $message = "[ERROR][$errno][$error][$file:$line]"; error_log($message); } |
Pass set_error_handler() the name of a function, and PHP forwards all errors to that function. The error handling function can take up to five parameters.
The first parameter is the error type, such as 8 for E_NOTICE. The second is the message thrown by the
error, such as “Undefined variable: html.”
The third and fourth arguments are the name of the file and the line number in which PHP detected the error.
The final parameter is an array holding all the variables defined in the current scope and their values.
For example, in this code, $html is appended to without first being assigned an initial value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
error_reporting(E_ALL); set_error_handler('pc_error_handler'); function pc_error_handler($errno, $error, $file, $line, $context) { $message = "[ERROR][$errno][$error][$file:$line]"; print "$message"; print_r($context); } $form = array('one','two'); foreach ($form as $line) { $html .= "<b>$line</b>"; } |
When the “Undefined variable” error is generated, pc_error_handler() prints:
1 |
[ERROR][8][Undefined variable: html][err-all.php:16] |
After the initial error message, pc_error_handler() also prints a large array containing all the global, environment, request, and session variables.