Curated by Carsonified

Learn with Treehouse

Accessibility, CSS3, Design, Django, HTML & CSS, HTML5, JavaScript, jQuery, NoSQL, PHP, Responsive Web Design, Ruby, Ruby on Rails, Tools, UX, Version Control, WordPress, iOS and more

Article 61

How to Debug in PHP

By

15 September 2009 | Category: Code, 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:

  1. Headers already sent. Try checking for white space at the head of your code or in files you’re including.
  2. You’re passing an incorrect number of parameters to a function.
  3. 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!

Follow @thinkvitamin on Twitter Please check out Treehouse

Other Posts You Might Find Interesting

  • Sorry - No Related Posts Found

Comments

  • http://www.meltdowntech.com Ben

    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.

  • http://rimantas.com/ Rimantas

    Wow, hungariant notation in dynamic language and system hungarian to add insult to injury. That was unexpected.

  • http://www.kieranmasterton.com Kieran Masterton

    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.

  • http://alicia.wilkersons.us/2009/09/15/carsonified-%c2%bb-how-to-debug-in-php/ Carsonified » How to Debug in PHP « Alicia Wilkerson

    [...] Carsonified » How to Debug in PHP. [...]

  • http://krues8dr.com Krues8dr

    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.

  • http://furiousball.com/inmydiatribe/?p=4521 furiousBlog – in my diatribe » Blog Archive » supergirl

    [...] How to Debug in PHP [...]

  • http://www.kieranmasterton.com Kieran Masterton

    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.

  • http://www.tschitschereengreen.com Jirka Schäfer

    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

  • http://www.kieranmasterton.com Kieran Masterton

    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.

  • http://www.kieranmasterton.com Kieran Masterton

    Though I should add that dedicated debugging libs and loggers do offer significant benefit to developers. So, point taken there :)

  • John

    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. :)

  • http://www.janilink.com Janilink

    Nice post Kieran, thanks for sharing it’s always cool when I can learn something new. Thanks

  • http://www.binaryage.com Antonin Hildebrand

    People considering FirePHP may also consider looking at my brand new tool FireLogger4PHP (http://firelogger4php.binaryage.com)

    And give it some love! thanks :-)

  • http://www.kieranmasterton.com Kieran Masterton

    Cheers John, glad you liked it.

  • http://www.kieranmasterton.com Kieran Masterton

    Thanks Janilink, glad you could learn something from the post :)

  • http://www.kieranmasterton.com Kieran Masterton

    Haha, nice plug :) I’m taking a look now, looks good, will check it out more thoroughly when I get a chance.

  • http://yeetorrents.com/news4/2009/09/15/carsonified-%c2%bb-how-to-debug-in-php/ » Carsonified » How to Debug in PHP – Yee Torrents News 4

    [...] Source:Carsonified » How to Debug in PHP [...]

  • http://www.metacomdesign.com/blog Ryan

    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!

  • http://wanderr.com/jay Jay Paroline

    Besides that, those notices help you catch typos.

  • http://wheresrhys.co.uk Rhys

    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

  • http://www.kieranmasterton.com Kieran Masterton

    Completely agree it’s really hard to find straightforward debugging advice in one place.

  • http://www.kieranmasterton.com Kieran Masterton

    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

  • http://www.about-webkinz.com/ webkinz

    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.

  • http://www.websdeveloper.com/think-vitamin-blog-how-to-debug-in-php/ Think Vitamin Blog: How to Debug in PHP | Webs Developer

    [...] 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 [...]

  • http://www.iskandrany.net iskandrany

    thanks for sharing your post

  • http://www.nortonsnapfitness.com bobbac

    {
    // 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

  • http://kintespace.com/rasxlog/?p=1893 the rasx() context » Blog Archive » “…the immediate availability of YUI 2.8.0” and other links…

    [...] 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: [...]

  • http://www.traffic-internet.net/?p=7080 Comment Déboguer en PHP | traffic-internet.net

    [...]  How to Debug in PHP (0 visite) [...]

  • http://twitter.com/nicoder nico

    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.

  • http://twitter.com/nicoder nico

    +1 :)))

  • http://www.vivanno.com/aggregator/?p=37094 vivanno.com::aggregator » Archive » Comment Déboguer en PHP

    [...]  How to Debug in PHP () [...]

  • http://mycoolgadget.co.uk/uk2ecommerce/ giftwagenseil

    Nice post, really had lot of good stuff. Keep up your good work

  • http://www.webhostright.com/ Web Host Right

    Thanks, im just learning about php at the moment so i found the article very useful, it’s nicely explained.

  • http://postcardformula.com Russell Brunson

    Russell Brunson teaches how to effectively use Postcard Marketing in the course titled Postcard Formula.
    Russell Brunson
    Postcard Marketing

  • http://www.killerbikegames.com BikeGames

    Thanks. I had learned PHP and now I understand.
    Bike Games

  • http://www.bojates.com Jemima

    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 ”;
    }

  • http://www.bojates.com Jemima

    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.

  • http://www.alive77.cn z.Yleo77

    useful for me… also i sometimes use zenddubug

  • Adam

    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.

  • http://www.kieranmasterton.com Kieran Masterton

    Thanks Adam, appreciate your comment.

  • http://blog.center.hu/2009/09/28/518/ PHP “hibátlanító” módszerek
  • http://www.drop-ship-reviews.com/ Nancy

    Good article. I am learning PHP5 and should be useful for me.

  • ken

    “The only other noisy thing of note is that foreach throws a Warning if given an empty array”

    ^^^ LOL

    RTFM

  • http://michaeldoyle.eu/blog/?p=382 PHP – How to Debug In PHP | Michael Doyle | Blog

    [...] 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. [...]

  • jason

    “White box ‘debugging’ in PHP” – fixed your title…

    Real debugging involves XDebug, Zend Debugger et. al.jason

  • http://otroblogmas.com/configurar-php-para-que-muestre-los-errores/ Configurar PHP para que muestre los errores | Otro Blog Más

    [...] Emezeta y Carsonified. Share this on del.icio.usShare this on FacebookTweet This!Share this on LinkedinDigg this!Post [...]

  • http://webdeveloperplus.com/php/25-new-useful-php-techniques-tutorials/ 25 New & Useful PHP Techniques & Tutorials

    [...] 24. How To Debug in PHP [...]

  • http://www.alholomalaraby.com aobeda

    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

    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. ,

  • http://link BadGirl26

    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

    Hungarian notation is such a big fail. It’a amateurism, I can’t believe this pass editorial review.

  • http://www.programmerfish.com/55-awesome-php-tutorials-for-noobs/ 55 Awesome PHP Tutorials for Noobs — ProgrammerFish – Everything that’s programmed!

    [...] 11)How to Debug in PHP Learn how to debug in PHP. [...]

  • http://donauweb.at Emile

    Have a look here, datadumper is var_dump in a much nicer and better way:
    http://sourceforge.net/projects/datadumper/

  • http://www.cenima.org/vb medo0

    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

  • http://www.etaf-lab.com/ etaf-lab

    hi
    i thank you alot for your interesting lesson.
    i wish you all luck

  • http://jesse.bilsten.net/2009/09/bookmarks-for-september-10th-through-september-16th/ Bookmarks for September 10th through September 16th | Jesse Bilsten

    [...] 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. [...]

  • http://www.touch-code-magazine.com/ Marin

    “Nobody enjoys the process of debugging their code.”
    Well I think you start on the wrong foot … when using a programming language fit for debugging, with a good debugger program and a IDE that integrates all the process, then it’s actually not a pain in the ass :) I’m talking Objective-C, gdb and XCode – just have a look at some screenshots here : http://clang-analyzer.llvm.org/

  • Suba

    Its really some useful tips for me

  • http://twitter.com/pzydog Hans Eugen

    Personally I prefer krumo( http://krumo.sourceforge.net/ ) over var_dump()

  • mom

    You’re forgetting the lightest and best debugging script out there: dBug (found at http://dbug.ospinto.com). Built to act just like ColdFusion’s cfdump. It’s amazing!!! Easy to use and very powerful. Saved me a LOT!!!!

  • http://avinash6784.wordpress.com Avinash Pawar

    Thanks, Nice article

Badges for Treehouse

Treehouse

Learn iOS, Rails, CSS3, jQuery, Node.js, HTML5, UX and more in less than 8 minutes per day. New videos added regularly. Sign up today and get a free Web Design Toolkit.

Ads Via The Deck

Think Vitamin Radio
Episode #34: Amazon Fire and Responsive Roundtable

Check out our bi-weekly radio show. Covering the hot topics on the web.

Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.

Download Podcast as mp3

Advisory Board

The Think Vitamin Advisory Board in place make sure that you receive the best content possible.