Using error_log() with print_r() to gracefully debug PHP

When debugging php code (especially Open Source code you have not written yourself) then to get a feeling of what is passed around when it doesn’t work I find that the print_r() function is very useful.

Trouble is that if you just throw in print_r() into the code where you think it is faulty then you can upset json, AJAX or your web page layouts as the print_r() splatters stuff to your displayed web page or in some cases the PHP file is not going to a browser (e.g. the PayPal IPN notify).

The trick is to throw it at the error log as follows e.g. if I was tracing what $number was being set to then I would use….

error_log(print_r($number,true));

note that you MUST set that print_r() option to “true” so that it returns a string. This string is then sent to the error_log() function which formats it with referrer details and puts it into the Apache error log.

Where does it end up ? Well on my test system on a non-vHost it is /var/log/apache2/error.log and on a vHosted server it is :/var/www/vhosts/<domain name>/statistics/logs/error_log so on your own system it will be a similar Apache error log file. Just tail that file to see what the messages are which will be something like this (in this example the $number was “2008” so the output for that error log message was,

[Sun Jan 01 13:21:12 2012] [error] [client 192.168.2.2] 2008, referer: http://19
2.168.2.250/bluebox/index.php/numbermanager/index

To synchronize the log messages with your testing then just look at the logging time.