6 PHP debugging tips for beginners

Get two monitors!

This should be obvious, and true for any development environment, but it took years for it to occur to me.   IDE’s at a pleasantly usable size take up a huge amount of screen real estate, and it’s much nicer to have a second monitor  dedicated to ebooks, user manuals, and Googling error messages/code issues,  A single very large, very high-res monitor might seem like an equally good solution, but I still find layers of windows inevitably stack up and must be annoying suffled through.

Forget about XAMPP, WAMP, MAMP, LAMP!

These all-inclusive packages are nice, but you should really install Apache, Mysql, and PHP separately as a learning exercise.  You don’t have to become guru, just get a feel for the configuration file locations and what the most important directives are.  It will build character, if nothing else.

Set error reporting level to maximum or near-maximum.

You can set the error level at runtime with:


<?php
error_reporting(E_ALL);
?>

Setting it to E_ALL & ~E_NOTICE is a bit more selective.   However,  on your development platform it is a better idea to make these changes in your php.ini file rather than at the runtime. If you get a syntax error with these options set in code and not in the php.ini file you may, depending on your set up, get a blank page.

Check the line immediately above the reported error!

It is quite common for a type in the line preceding the error message to be the culprit.

Var_dump(), print_r() and get_defined_vars() are your friends!

Dumping variables or even the entire symbol table by default to the development version of a web page is an enormous time saver.  Some development blogs recommend posting the output to the viewable page itself using <pre> tags.  I prefer to enclose the output in HTML comment tags and inspect using “View Source” as other HTML syntax errors could result in a completely blank page being displayed.

To dump the entire symbol table visible at a given scope include this:

<?php
echo "<!--n";
print_r(get_defined_vars());
echo "--!>n";
?>

Automatically and selectively dumping just a few globals right after the <body> tag can also be useful:

<?php
echo "<!--n";
print_r($_GET);
print_r($_POST
echo "--!>n";
?>

Firebug, FirePHP, and Web Developer plugins for Firefox.

‘Nuff said.   These are also useful for examinng HTML and CSS.