PHP: sending emails whenever an error occurs
Problem
PHP, by default, displays an error directly in the user’s browser. Something like this is common around the web:
Notice: Undefined variable: name in /abc/public_html/index.php on line 29
This is not so useful because if someone else caused this error you have no way of knowing about it and because potentially sensitive information about your PHP code is leaking.
Solution
set_error_handler() can be used to change the way PHP deals with errors by specifying a custom function to be called. Now you can easily output any message you want to the client, keeping the error details to yourself.
set_error_handler("myErrorHandler",E_ALL);
I’ve used E_ALL because I want to know all the error types that occur. Now the only thing left to do is create the myErrorHandler() function in which you print a message to your user and also email the sensitive error details to your own address:
function myErrorHandler($errno, $errstr, $errfile, $errline){
$message = '<p>Error number <strong>'.$errno.'</strong>
was encountered in <strong>'.$errfile.'</strong>
on line <strong>'.$errline.'</strong>
<br />
'.$errstr.'
</p>';
mail("youremail@example.com","Error at yourWebsite",$message,"Content-type: text/html; charset=utf-8");
echo "<div class=\"error\">Script error detected.</div>";
return true;
}
You may also include any debug info in your message, such as the $_SERVER['REQUEST_URI'], time, the user who generated the error (if you have a website with users) etc.
If you want to work with uncaught exceptions, use the set_exception_handler() function instead. It works the same way as set_error_handler().
This is a PHP equivalent to the Exception Notifier in Ruby on Rails.
