15 September 2009
How to Debug in PHP
Nobody enjoys the process of debugging their code. If you want to build killer web apps though, it’s vital that you understand the process thoroughly.
This article breaks down the fundamentals of debugging in PHP, helps you understand PHP’s error messages and introduces you to some useful tools to help make the process a little less painful.
Editor’s Note: We’ll be running workshops like “How to Build a Web App from A-Z” at The Future of Web Apps London.
Doing your Ground Work
It is important that you configure PHP correctly and write your code in such a way that it produces meaningful errors at the right time. For example, it is generally good practice to turn on a verbose level of error reporting on your development platform. This probably isn’t such a great idea, however, on your production server(s). In a live environment you neither want to confuse a genuine user or give malicious users too much information about the inner-workings of your site.
So, with that in mind lets talk about the all too common “I’m getting no error message” issue. This is normally caused by a syntax error on a platform where the developer has not done their ground work properly. First, you should turn display_errors on. This can be done either in your php.ini file or at the head of your code like this:
<?php
ini_set('display_errors', 'On');
Tip: In these code examples I omit the closing (?>) PHP tag. It is generally considered good practice to do so in files which contain only PHP code in order to avoid accidental injection of white space and the all too common “headers already sent” error.
Next, you will need to set an error reporting level. As default PHP 4 and 5 do not show PHP notices which can be important in debugging your code (more on that shortly). Notices are generated by PHP whether they are displayed or not, so deploying code with twenty notices being generated has an impact upon the overhead of your site. So, to ensure notices are displayed, set your error reporting level either in your php.ini or amend your runtime code to look like this:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
Tip: E_ALL is a constant so don’t make the mistake of enclosing it in quotation marks.
With PHP 5 it’s also a good idea to turn on the E_STRICT level of error reporting. E_STRICT is useful for ensuring you’re coding using the best possible standards. For example E_STRICT helps by warning you that you’re using a deprecated function. Here’s how to enable it at runtime:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
It is also worth mentioning that on your development platform it is often a good idea to make these changes in your php.ini file rather than at the runtime. This is because if you experience a syntax error with these options set in your code and not in the php.ini you may, depending on your set up, be presented with a blank page. Likewise, it is worth noting that if you’re setting these values in your code, a conditional statement might be a good idea to avoid these settings accidentally being deployed to a live environment.
What Type of Error am I Looking at?
As with most languages, PHP’s errors may appear somewhat esoteric, but there are in fact only four key types of error that you need to remember:
1. Syntax Errors
Syntactical errors or parse errors are generally caused by a typo in your code. For example a missing semicolon, quotation mark, brace or parentheses. When you encounter a syntax error you will receive an error similar to this:
Parse error: syntax error, unexpected T_ECHO in /Document/Root/example.php on line 6
In this instance it is important that you check the line above the line quoted in the error (in this case line 5) because while PHP has encountered something unexpected on line 6, it is common that it is a typo on the line above causing the error. Here’s an example:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$sSiteName = "Think Vitamin"
echo $sSiteName;
In this example I have omitted the semi-colon from line 5, however, PHP has reported an error occurred on line 6. Looking one line above you can spot and rectify the problem.
Tip: In this example I am using Hungarian Notation. Adopting this coding standard can aid with debugging code while working collaboratively or on a piece of code you wrote some time ago. The leading letter denoting the variable type means that determining a variable type is very quick and simple. This can aid in spotting irregularities which can also help highlight any potential logic errors.
2. Warnings
Warnings aren’t deal breakers like syntax errors. PHP can cope with a warning, however, it knows that you probably made a mistake somewhere and is notifying you about it. Warnings often appear for the following reasons:
- Headers already sent. Try checking for white space at the head of your code or in files you’re including.
- You’re passing an incorrect number of parameters to a function.
- Incorrect path names when including files.
3. Notices
Notices aren’t going to halt the execution of your code either, but they can be very important in tracking down a pesky bug. Often you’ll find that code that’s working perfectly happily in a production environment starts throwing out notices when you set error_reporting to E_ALL.
A common notice you’ll encounter during development is:
>Notice: Undefined index: FullName in /Document/Root/views/userdetails.phtml on line 55
This information can be extremely useful in debugging your application. Say you’ve done a simple database query and pulled a row of user data from a table. For presentation in your view you’ve assigned the details to an array called $aUserDetails. However, when you echo $aUserDetails['FirstName'] on line 55 there’s no output and PHP throws the notice above. In this instance the notice you receive can really help.
PHP has helpfully told us that the FirstName key is undefined so we know that this isn’t a case of the database record being NULL. However, perhaps we should check our SQL statement to ensure we’ve actually retrieved the user’s first name from the database. In this case the notice has helped us rule out a potential issue which has in turn steered us towards the likely source of our problem. Without the notice our likely first stop would have been the database record, followed by tracing back through our logic to eventually find our omission in the SQL.
4. Fatal Errors
Fatal Errors sound the most painful of the four but are in fact often the easiest to resolve. What it means, in short, is that PHP understands what you’ve asked it to do but can’t carry out the request. Your syntax is correct, you’re speaking its language but PHP doesn’t have what it needs to comply. The most common fatal error is an undefined class or function and the error generated normally points straight to the root of the problem:
Fatal error: Call to undefined function create() in /Document/Root/example.php on line 23
Using var_dump() to Aid Your Debugging
var_dump() is a native PHP function which displays structured, humanly readable, information about one (or more) expressions. This is particularly useful when dealing with arrays and objects as var_dump() displays their structure recursively giving you the best possible picture of what’s going on. Here’s an example of how to use var_dump() in context:
Below I have created an array of scores achieved by users but one value in my array is subtly distinct from the others, var_dump() can help us discover that distinction.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$aUserScores = array('Ben' => 7,'Linda' => 4,'Tony' => 5,'Alice' => '9');
echo '<pre>';
var_dump($aUserScores);
echo '</pre>';
Tip: Wrap var_dump() in <pre> tags to aid readability.
The output from var_dump() will look like this:
array(4) {
["Ben"]=>
int(7)
["Linda"]=>
int(4)
["Tony"]=>
int(5)
["Alice"]=>
string(1) "9"
}
As you can see var_dump tells us that $aUserScores is an array with four key/value pairs. Ben, Linda, and Tony all have their values (or scores) stored as integers. However, Alice is showing up as a string of one character in length.
If we return to my code, we can see that I have mistakenly wrapped Alice’s score of 9 in quotation marks causing PHP to interpret it as a string. Now, this mistake won’t have a massively adverse effect, however, it does demonstrate the power of var_dump() in helping us get better visibility of our arrays and objects.
While this is a very basic example of how var_dump() functions it can similarly be used to inspect large multi-dimensional arrays or objects. It is particularly useful in discovering if you have the correct data returned from a database query or when exploring a JSON response from say, Twitter:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$sJsonUrl = 'http://search.twitter.com/trends.json';
$sJson = file_get_contents($sJsonUrl,0,NULL,NULL);
$oTrends = json_decode($sJson);
echo '<pre>';
var_dump($oTrends);
echo '</pre>';
Useful Tools to Consider when Debugging
Finally, I want to point out a couple of useful tools that I’ve used to help me in the debugging process. I won’t go into detail about installing and configuring these extensions and add-ons, but I wanted to mention them because they can really make our lives easier.
Xdebug
Xdebug is a PHP extension that aims to lend a helping hand in the process of debugging your applications. Xdebug offers features like:
- Automatic stack trace upon error
- Function call logging
- Display features such as enhanced var_dump() output and code coverage information.
Xdebug is highly configurable, and adaptable to a variety of situations. For example, stack traces (which are extremely useful for monitoring what your application is doing and when) can be configured to four different levels of detail. This means that you can adjust the sensitivity of Xdebug’s output helping you to get granular information about your app’s activity.
Stack traces show you where errors occur, allow you to trace function calls and detail the originating line numbers of these events. All of which is fantastic information for debugging your code.
Tip: As default Xdebug limits var_dump() output to three levels of recursion. You may want to change this in your xdebug.ini file by setting the xdebug.var_display_max_depth to equal a number that makes sense for your needs.
Check out Xdebug’s installation guide to get started.
FirePHP
For all you FireBug fans out there, FirePHP is a really useful little PHP library and Firefox add-on that can really help with AJAX development.
Essentially FirePHP enables you to log debug information to the Firebug console using a simple method call like so:
<?php
$sSql = 'SELECT * FROM tbl';
FB::log('SQL query: ' . $sSql);
In an instance where I’m making an AJAX search request, for example, it might be useful to pass back the SQL string my code is constructing in order that I can ensure my code is behaving correctly. All data logged to the Firebug console is sent via response headers and therefore doesn’t effect the page being rendered by the browser.
Warning: As with all debug information, this kind of data shouldn’t be for public consumption. The downside of having to add the FirePHP method calls into your PHP is that before you go live you will either have to strip all these calls out or set up an environment based conditional statement which establishes whether or not to include the debug code.
You can install the Firefox add-on at FirePHP’s website and also grab the PHP libs there too. Oh, and don’t forget if you haven’t already installed FireBug, you’ll need that too.
In Conclusion …
Hopefully during the course of this article you have learned how to do your ground work by preparing PHP for the debugging process; recognise and deal with the four key PHP error types and use var_dump() to your advantage. Likewise, I hope that you will find Xdebug and FirePHP useful and that they will make your life easier during your development cycle.
As I’ve already mentioned, and I really can’t say this enough, always remember to remove or suppress your debug output when you put your sites into production after all there’s nothing worse than all your users being able to read about your errors in excruciating detail.
Got a great debugging tip to share? Do you use a great little PHP extension that makes your bug trapping life easier? Please tell us about them in comments below!

We're big fans of 


Ben
# September 15, 2009 - 10:22 am
I also use these two functions to help speed up any debugging:
function debug_r($arr,$title=”) {
// quickly output an array / object, title [optional]
if($title==”) {
echo(“debug_r”);
} else {
echo(“debug_r – “.$title.”");
}
echo(“”.print_r($arr,true).”");
}
function debug_e($message) {
// replacement for echo, with built in
echo($message.”");
}
usage:
debug_r($myArr,”Debug #1″);
debug_e($myStr);
Saves having to keep typing in the s, especially as this involves many open and close brackets where more little errors can occur.
Rimantas
# September 15, 2009 - 11:06 am
Wow, hungariant notation in dynamic language and system hungarian to add insult to injury. That was unexpected.
Kieran Masterton
# September 15, 2009 - 11:29 am
Hi Rimantas, yeah I follow you, and I’ve had this discussion numerous times in the past, I just think it aids with readability and understanding. But, I take your point too.
nico
# September 17, 2009 - 1:31 pm
I used to think it helped too. But now that I try to keep my code in really small functions, I find I do not need hungarian notation any more. Since the initialisation of a variable is never far from the last place where it is used, it’s really easy to see what type the variable is.
And i think that $users is more readable than $aUsers. Personal preference i guess.
Carsonified » How to Debug in PHP « Alicia Wilkerson
# September 15, 2009 - 12:14 pm
[...] Carsonified » How to Debug in PHP. [...]
Krues8dr
# September 15, 2009 - 1:17 pm
E_NOTICE throws a message any time you use a variable or index that hasn’t been declared, so I usually ignore that – it’s just not useful. If I’m debugging a many-tiered application, (E_ALL | E_STRICT) ^ E_NOTICE is a pretty safe bet, without being overwhelmed by messages. The only other noisy thing of note is that foreach throws a Warning if given an empty array, and you don’t really need to test this before each use.
Kieran Masterton
# September 15, 2009 - 1:42 pm
That’s my point, those Notices are important and you NEED to see them in a development enviroment. If your code is throwing out Notices you need to address those Notices even if it’s just an undeclared variable or index. Afterall, PHP generates those Notices whether they’re being displayed or not, so a whole load of notices on a page is causing you unnecessary overhead.
Jay Paroline
# September 16, 2009 - 4:43 am
Besides that, those notices help you catch typos.
ken
# October 6, 2009 - 6:45 am
“The only other noisy thing of note is that foreach throws a Warning if given an empty array”
^^^ LOL
RTFM
furiousBlog – in my diatribe » Blog Archive » supergirl
# September 15, 2009 - 1:36 pm
[...] How to Debug in PHP [...]
Jirka Schäfer
# September 15, 2009 - 3:00 pm
using var_dump() is a really bad practice for odd php hackers. this is a huge security issue and should be avoided. serious php coders are using loggers and dedicated debug libs…
echo, print and var_dump debugging is a php mentality which shows a lack of professional code creation attitude which is widely spread under php developers
Adam
# September 26, 2009 - 12:18 pm
Wow, someone sounds pretty full of himself. Thee are basic tools that should be in every dev’s toolkit. Not everyone has the time, experience, or resources to make use of full on debuggers. Also, many people are just writing a script or two and have no need for a full debugger.
Your quick, inaccurate assessment of the tools covered here exposes you as inexperienced and a barggard – parhaps you should stay out of the conversation until you have something constructive to say.
Thanks for the great article Kieran.
Kieran Masterton
# September 26, 2009 - 2:05 pm
Thanks Adam, appreciate your comment.
Kieran Masterton
# September 15, 2009 - 3:23 pm
This article was chiefly written with native functions in mind and not tailored towards a specific debugging library or logger. Therefore, I feel that the methods you describe are outside the scope of this article.
I am by no means advocating that anyone deploys anything to a live environment with var_dump code still in place. I was just discussing the extra level of verbosity it provides when trying to track down a problem in your code.
Kieran Masterton
# September 15, 2009 - 3:25 pm
Though I should add that dedicated debugging libs and loggers do offer significant benefit to developers. So, point taken there :)
John
# September 15, 2009 - 3:58 pm
Nice post Kieran, thanks for sharing your know-how. I would love to see a mention of TDD, or using TDD tools, as a means of preventing errors and lowering debug time. :)
Kieran Masterton
# September 15, 2009 - 9:19 pm
Cheers John, glad you liked it.
nico
# September 17, 2009 - 1:33 pm
+1 :)))
Janilink
# September 15, 2009 - 8:44 pm
Nice post Kieran, thanks for sharing it’s always cool when I can learn something new. Thanks
Kieran Masterton
# September 15, 2009 - 9:20 pm
Thanks Janilink, glad you could learn something from the post :)
Antonin Hildebrand
# September 15, 2009 - 8:57 pm
People considering FirePHP may also consider looking at my brand new tool FireLogger4PHP (http://firelogger4php.binaryage.com)
And give it some love! thanks :-)
Kieran Masterton
# September 15, 2009 - 9:24 pm
Haha, nice plug :) I’m taking a look now, looks good, will check it out more thoroughly when I get a chance.
» Carsonified » How to Debug in PHP - Yee Torrents News 4
# September 15, 2009 - 10:24 pm
[...] Source:Carsonified » How to Debug in PHP [...]
Ryan
# September 16, 2009 - 1:33 am
Great article. When I first started learning PHP (and the frustrations that came along with it) I really lacked the know how of how to debug. After countless amounts of time researching, you still pointed out some tips that I wasn’t familiar with. Thanks!
Kieran Masterton
# September 16, 2009 - 10:50 am
Completely agree it’s really hard to find straightforward debugging advice in one place.
Rhys
# September 16, 2009 - 5:52 am
Thank you, thank you, thank you.
My php debuggings always been a bit too much trial and error. This article will really help me identify and solve problems quicker. Like the screencast by snook.ca that first introduced me to firebugs advanced js debugging features, I think this article will improve my coding speed no end.
Im also slightly gobsmacked that people Ive worked for, who were supposed to be training me on php, never once mentioned var_dump()!
Cheers
Kieran Masterton
# September 16, 2009 - 10:56 am
No probs Rhys, glad the article helped. There’s a nasty culture amongst some developers, especially I find in the PHP world, of residence to any form of knowledge transfer. It’s something I’ve always been uncomfortable with because I believe that some of the best work comes out of being collaborative and sharing experience and know-how.
Thanks for your comment,
K
webkinz
# September 16, 2009 - 2:47 pm
Awesome! I have read a lot on this topic, but you definitely give it a good vibe. This is a great post. Glad to see getting some much deserved attention. Awesome work. can’t wait to see more stuff done by you.
Think Vitamin Blog: How to Debug in PHP | Webs Developer
# September 16, 2009 - 6:01 pm
[...] the Think Vitamin blog Kieran Masterson has put together an article about debugging PHP applications – everything from error levels out to a few useful tools that can [...]
iskandrany
# September 17, 2009 - 12:05 am
thanks for sharing your post
bobbac
# September 17, 2009 - 7:28 am
{
// quickly output an array / object, title [optional]
if($title==”) {
echo(”debug_r”);
} else {
echo(”debug_r – “.$title.””);
}
echo(””.print_r($arr,true).””);
}
function debug_e($message) {
// replacement for echo, with built in
echo($message.””);
}
norton gym
gyms in norton
honda 1800
goldwing 1800
the rasx() context » Blog Archive » “…the immediate availability of YUI 2.8.0” and other links…
# September 17, 2009 - 12:37 pm
[...] Carsonified: “FirePHP …For all you FireBug fans out there, FirePHP is a really useful little PHP library and Firefox add-on that can really help with AJAX development. …Essentially FirePHP enables you to log debug information to the Firebug console using a simple method call like so: [...]
Comment Déboguer en PHP | traffic-internet.net
# September 17, 2009 - 1:18 pm
[...] How to Debug in PHP (0 visite) [...]
vivanno.com::aggregator » Archive » Comment Déboguer en PHP
# September 17, 2009 - 1:45 pm
[...] How to Debug in PHP () [...]
giftwagenseil
# September 17, 2009 - 3:09 pm
Nice post, really had lot of good stuff. Keep up your good work
Web Host Right
# September 17, 2009 - 8:43 pm
Thanks, im just learning about php at the moment so i found the article very useful, it’s nicely explained.
Russell Brunson
# September 20, 2009 - 5:26 pm
Russell Brunson teaches how to effectively use Postcard Marketing in the course titled Postcard Formula.
Russell Brunson
Postcard Marketing
BikeGames
# September 21, 2009 - 12:42 am
Thanks. I had learned PHP and now I understand.
Bike Games
Jemima
# September 23, 2009 - 12:34 pm
I use this small function to display debugging code. It just wraps tags around what is passed in which makes it easier to read. You can pass in variables including arrays or just put your own text.
e.g.
print_pre(“loaded all include files”);
print_pre($_POST);
etc.
function print_pre($array) {
echo ”;
print_r($array);
echo ”;
}
Jemima
# September 23, 2009 - 3:44 pm
Aha! I have just realised that this strips the pre tags from all the functions that have been posted. So, I couldn’t understand what the previous functions were doing, and the one I’ve posted, which does the same, now doesn’t make sense either.
Sorry, all, for the repetition, and, to clarify for others: where it shows a meaningless echo, that should be an opening and then closing pre tag.
z.Yleo77
# September 26, 2009 - 12:18 pm
useful for me… also i sometimes use zenddubug
PHP “hibátlanító” módszerek
# September 28, 2009 - 7:51 am
[...] http://carsonified.com/blog/dev/how-to-debug-in-php/ [...]
Nancy
# September 28, 2009 - 12:11 pm
Good article. I am learning PHP5 and should be useful for me.
PHP – How to Debug In PHP | Michael Doyle | Blog
# October 6, 2009 - 12:35 pm
[...] Carsonified has a good blog entry about how to debug in PHP. It outlines the 4 php error types, using var_dump() and recommends some tools to help with debugging. [...]
網站製作學習誌 » [Web] 連結分享
# October 7, 2009 - 11:37 am
[...] How to Debug in PHP [...]
jason
# October 9, 2009 - 11:33 am
“White box ‘debugging’ in PHP” – fixed your title…
Real debugging involves XDebug, Zend Debugger et. al.jason
Configurar PHP para que muestre los errores | Otro Blog Más
# October 12, 2009 - 7:18 am
[...] Emezeta y Carsonified. Share this on del.icio.usShare this on FacebookTweet This!Share this on LinkedinDigg this!Post [...]
25 New & Useful PHP Techniques & Tutorials
# October 16, 2009 - 2:21 pm
[...] 24. How To Debug in PHP [...]
aobeda
# October 19, 2009 - 3:29 pm
Great article. When I first started learning PHP (and the frustrations that came along with it) I really lacked the know how of how to debug. After countless amounts of time researching, you still pointed out some tips that I wasn’t familiar with. Thanks
BadGirl26
# October 22, 2009 - 11:23 pm
From the programming and service side, youth development frameworks are also moving away from deficit models, valuing instead young people for their potential, and designing interventions to build a set of core competencies needed to participate successfully as adolescents and adults. ,
nemke
# October 24, 2009 - 5:58 pm
Hungarian notation is such a big fail. It’a amateurism, I can’t believe this pass editorial review.
55 Awesome PHP Tutorials for Noobs — ProgrammerFish - Everything that's programmed!
# October 29, 2009 - 5:33 am
[...] 11)How to Debug in PHP Learn how to debug in PHP. [...]
Emile
# October 30, 2009 - 11:00 am
Have a look here, datadumper is var_dump in a much nicer and better way:
http://sourceforge.net/projects/datadumper/
55 خودآموز PHP براي تازه كار ها « برنامه نويسي دلفي، سي شارپ ، ويژوال بيسيك ، دات نت
# November 2, 2009 - 9:14 pm
[...] 11)How to Debug in PHP Learn how to debug in PHP. [...]
medo0
# November 29, 2009 - 3:01 am
this is wonderful tutorial .. i read it 3 times and get a fantastic results and sure i put a
copy of this lesson on my site here
http://www.cenima.org
etaf-lab
# December 8, 2009 - 9:20 am
hi
i thank you alot for your interesting lesson.
i wish you all luck
Bookmarks for September 10th through September 16th | Jesse Bilsten
# December 11, 2009 - 4:48 pm
[...] Carsonified » How to Debug in PHP – This article breaks down the fundamentals of debugging in PHP, helps you understand PHP’s error messages and introduces you to some useful tools to help make the process a little less painful. [...]