PHP Error Handling

Dec 27, 2010

Over this past summer, one of my tasks was to integrate active directory with a ticket management software for a local school district. This software was probably written ten years ago when PHP 4 was defacto, using superglobals to access POST/GET data was not the norm, and before the rise of the MVC architecture on the web. Since the code was so tightly coupled, rewriting the authentication system meant rewriting code in almost every file. I probably would have threw out the entire code base and started fresh, but the budget was tight and I wanted experience working with someone else''s code other than my own. For the most part, the code has been successfully deployed and over the past few months, a few thousand tickets have been submitted. However, occasionally users complain they get errors when using the system (and of course never provide any useful feedback as to how to replicate the error). Sure, I could turn error reporting off, but the errors would go unnoticed and never get fixed. I did the opposite. I turned error reporting on as high as it would go and created a custom error handler that would email me diagnostic information each time an error, warning, or notice happened. For the first few days my inbox was flooded with messages from undefined variables (lesson learned), but the messages have fizzled down to almost nothing. Below is the error handler is use:

error_reporting(E_ALL & E_NOTICE);

function error_handler($errno, $errstr, $errfile, $errline) 
    if (!(error_reporting() & $errno)) {
    echo $errno . " " . $errstr . "\n\n";
    echo "\n";
    echo "\n";
    echo "\n";
    echo "\n";
    $body = ob_get_contents();
    mail('', 'Software Error', $body);
    return false;
$old = set_error_handler("error_handler");