Several days back, S Beam (I don’t know the person’s name) posted a tip to the eVolt list that presented a way to use PHP’s native set_Error_handler() and trigger_error() functions to generate an e-mail “containing a full debugging dump concerning any error to the developers, while providing a nice, innocuous, non-heart-attack-inducing message to the user.” As I really like the concept, and hope to start using it in future projects (and may well go back and add it to older scripts), I decided to post it here for easy retrieval, and to pass the knowledge along to other developers. While I would normally include something like this in a blockquote, I am making an exception in this case as I want as much room as possible for the code, and because I have made some slight modifications to the code. Everything between the horizontal rules is from the original post.
In your init.php script (or equivalent that is prepended to every invocation of php) have the line
set_error_handler ('my_error_handler');
then write a function like this:
function my_error_handler ($errno, $errstr, $errfile, $errline) {
mail(ERROR_RECIPIENT, "Site ERROR", "Error $errno at $errline of
$errfile: [$errstr]"); // Eliminate the carriage return
// Other code to execute, including user error message generation
print "I am the user error message"; // Shown on screen
}
Then in your application, when you come across a condition where you would have used die() or exit(), just do this, e.g.:
trigger_error("Couldn't connect to the DB!", E_USER_ERROR);
Season to taste. The mail will go out and you will not need to hope the user will call you and read the error message to you or anything like that. You could also include a dump of all POST, GET, SESSION or any other variables in your mail to see exactly what the state was when the error occurred.
I look forward to trying this out as I think it could prove to be a great boon for the various Web apps that I have developed, adapted and/or installed.