PHP Debugging with Style -OR- How I Learned to Stop Worrying and Love the Bug

This is a very old article. It has been imported from older blogging software, and the formatting, images, etc may have been lost. Some links may be broken. Some of the information may no longer be correct. Opinions expressed in this article may no longer be held.

PHP lets you define your own error handler, so I decided to get a bit fancy. MegaErrorHandler (MEH) outputs its errors as specially-formatted HTML comments, with the details of the error encoded using JSON.

A small client-side script, with an associated stylesheet then pulls this data out of the comments and formats it as a nice little interactive bug-viewing console, allowing you to view a stack trace for each bug, inspect superglobals, view the syntax-highlighted source code for the file where the error occurred, check the list of defined constants and other useful things.

It severely bloats the pages, but then again, you only really only want to use this while your testing a site — not once it’s live, as it reveals too much information about the internals of your server, so could be a security risk. When live, you’d set the output mode to DEBUG_SILENT instead of DEBUG_JSON as in the example.

It requires either PHP 5.2.x or above; or PHP 5.0.x/5.1.x with PEAR’s Services_JSON module.

Example of usage:


Example usage
These will cause a few errors!

\n”;
echo $foo; // error: undefined variable
echo $_GET[bar]; // error: undefined constant, nonexistant array index
trigger_error(‘Test error. 1, 2, 3.’); // error: user triggered

function lalala ()
{
$msg = “Last error message.\n”;
echo $mgs; // error: undefined variable
}
lalala();
?>

Output of above example

MegaErrorHandler/0.2.3

Supported browsers: Opera 9.x, Firefox 1.5.x.

MegaErrorHandler.class.php (Highlighted source code)
handler.js
handler.css

(Why is the version number for the first release 0.2.3? Because MEH is part of the demiblog project, so I’m keeping version numbers pegged with that. MEH doesn’t require any other parts of demiblog to work though — you can use it in your own projects with no extra dependencies.)