How can a custom error handling function be implemented in PHP to send error messages via email?
To implement a custom error handling function in PHP that sends error messages via email, you can use the `set_error_handler()` function to set a custom error handler. Within this custom error handler, you can check for the error type and send an email notification containing the error message, file, line number, and any other relevant information.
<?php
// Custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
$error_message = "Error: $errstr in $errfile on line $errline";
$subject = "Error Notification";
$to = "your@email.com";
$headers = "From: webmaster@example.com";
// Send email notification
mail($to, $subject, $error_message, $headers);
// Log the error to a file or database
error_log($error_message, 3, "error.log");
}
// Set custom error handler
set_error_handler("customErrorHandler");
// Trigger a sample error
echo $undefined_variable;
?>
Related Questions
- In the provided code snippet, what are the common pitfalls related to using the mysql_query function and handling its results?
- Is it advisable to combine POST and GET parameters in a form submission for PHP scripts, and what are the implications of doing so?
- What potential issues can arise when dealing with timestamps in PHP and MySQL databases?