Problem:
Although the set_error_handler() function is effective for capturing most PHP errors, it fails to handle fatal errors, such as calling nonexistent functions. This leaves developers seeking alternative methods for capturing these critical errors.
Solution:
PHP 5.2 provides the register_shutdown_function() function that enables capturing of fatal errors. Here's an implementation to send error emails upon encountering such errors:
register_shutdown_function("fatal_handler"); function fatal_handler() { $error = error_get_last(); // Obtain last error if ($error !== NULL) { $errno = $error["type"]; $errfile = $error["file"]; $errline = $error["line"]; $errstr = $error["message"]; error_mail(format_error($errno, $errstr, $errfile, $errline)); } }
Supporting Functions:
Define the necessary supporting functions, such as format_error and error_mail. The format_error function can return the error information in a table format:
function format_error($errno, $errstr, $errfile, $errline) { $trace = print_r(debug_backtrace(false), true); $content = <<<HTML <table> <thead><th>Item</th><th>Description</th></thead> <tbody> <tr><th>Error</th><td><pre class="brush:php;toolbar:false">$errstr
$errno
$trace
Utilize Swift Mailer library to implement the error_mail function.
Additional Resources:
The above is the detailed content of How Can I Catch and Handle Fatal PHP Errors (E_ERROR) Using `register_shutdown_function()`?. For more information, please follow other related articles on the PHP Chinese website!