How can a "Fatal error" be handled in PHP to trigger a specific action, such as sending an email with error details?
When a "Fatal error" occurs in PHP, it typically stops the script execution immediately, making it difficult to handle and log the error details. To handle a "Fatal error" and trigger a specific action, such as sending an email with error details, you can use a combination of the register_shutdown_function() function and the error_get_last() function. By registering a shutdown function that checks for the last error and sends an email if it is a fatal error, you can ensure that critical errors are logged and action is taken.
register_shutdown_function(function() {
$error = error_get_last();
if ($error !== null && $error['type'] === E_ERROR) {
$error_message = "Fatal error: " . $error['message'] . " in " . $error['file'] . " on line " . $error['line'];
// Send an email with the error details
$to = "your@email.com";
$subject = "Fatal Error";
$message = $error_message;
$headers = "From: webmaster@example.com";
mail($to, $subject, $message, $headers);
}
});
Keywords
Related Questions
- How can setting the content type and charset impact the display of special characters in PHP?
- In what scenarios would using an iframe to display images from a PHP script be considered acceptable or appropriate?
- What are the best practices for managing and updating content in a database using PHP for a website with multiple pages?