Web development with PHP can get frustrating without the adequate tools. The most common thing a new web developer does when attempting PHP debugging is to add
var_dump() calls to print out the value of a variable at a certain point in the program’s execution, in conjunction with an
Doing this will reveal the values of the variable you’re trying to check, but it requires you to add and remove lines in your code, and more often than not, those lines are forgotten to be removed, so they end up as bugs in the code.
A good way to develop your code is with test driven development, using unit tests to verify the output of your methods. But sometimes there are parts of the code that cannot be easily tested. For these cases using a proper step by step debugger is a better tool for the job. Xdebug is a PHP extension that does the job. With Xdebug you can set breakpoints in your code, display the contents of constants like
$_SESSION, give you a trace of the execution around the breakpoint or uncaught exception, and follow the values of any variables you want. You can also profile your application to detect performance bottlenecks.
There are several ways to install Xdebug on your development system. On a Debian-based system you install it with the following command:
sudo aptitude install php5-xdebug
For other systems and custom installations there is an installation Wizard, following the steps in the page will provide you with the instructions needed for your particular case.
Then check your php.ini file to configure the Xdebug extension to your liking. Check the documentation for all the features and options. Here’s a sample of the options:
xdebug.remote_enable=1 xdebug.remote_handler=dbgp xdebug.remote_host=127.0.0.1 xdebug.remote_port=9000 xdebug.remote_mode=req xdebug.idekey=default xdebug.remote_log="/var/log/xdebug/xdebug.log" xdebug.show_exception_trace=0 xdebug.show_local_vars=9 xdebug.var_display_max_depth=10 xdebug.show_mem_delta=0 xdebug.trace_format=0 xdebug.profiler_enable=1 xdebug.profiler_output_dir="/tmp/xdebug/"
xdebug.show_local_vars will display the number of local variables available at the breakpoint, so no need of several
var_dump() calls for each variable you want to see. The
xdebug.var_display_max_depth changes how many nested levels of arrays or objects will be displayed, where by default,
var_dump() will only display 3 levels down. There are more interesting data display options in the documentation.
Make sure the remote log directory and profiler output directories exist in your system. Restart your web server and you’re good to go.
phpinfo() output page should now display a section like this:
Now, here are some links to setup and use your development environment with Xdebug, depending on what you use.
- Emacs with Geben
- Eclipse IDE (also applies for Aptana)
- FirePHPbug a Firefox extension like Firebug
- Notepad++ Editor
Hope this helps and happy coding!