Handling Parse and Fatal Errors Using a Custom Error Handler
While it is generally assumed that custom error handlers cannot handle parse and fatal errors, this is not entirely accurate. By utilizing a different approach, we can indeed trap and handle these errors using a custom error handler.
Using a Shutdown Function
The key to handling parse and fatal errors is to employ a shutdown function registered with register_shutdown_function(). This function will be invoked upon script termination, allowing us to intercept any uncaught errors.
Error Pre-handler (prepend.php)
To ensure that the error handler is accessible to all PHP scripts, consider prepending a file like prepend.php as follows:
set_error_handler("errorHandler"); register_shutdown_function("shutdownHandler");
Error Handler (errorHandler)
This function will handle errors based on their level and log them appropriately:
function errorHandler($error_level, $error_message, $error_file, $error_line, $error_context) { // Handle errors according to $error_level and log them using mylog() }
Shutdown Handler (shutdownHandler)
Upon script termination, this function will handle any remaining uncaught errors:
function shutdownHandler() { $lasterror = error_get_last(); // Handle last error based on its type and log it using mylog() }
Log Function (mylog)
This function is used to log errors to the desired location, such as a database or file.
Implementation
By setting up this custom error handling mechanism, we can now handle all error levels, including parse and fatal errors. The error handling will be consistent across all scripts that have the prepend.php file included.
Considerations
PHP.ini Configuration
To automatically prepend prepend.php to all PHP scripts, add the following line to php.ini:
auto_prepend_file = "/homepages/45/d301354504/htdocs/hmsee/cgi-bin/errorhandling.php"
This approach provides a comprehensive solution for handling parse and fatal errors using a custom error handler.
The above is the detailed content of Can Custom Error Handlers Really Catch Parse and Fatal Errors in PHP?. For more information, please follow other related articles on the PHP Chinese website!