whenpenguinsattack.com

Wednesday, February 08, 2006

Debugging Php

by David Sklar

Whether you're a PHP newbie or a wizard, your programs are going to have bugs in them. Nobody's perfect.

This article gives you some techniques for finding and fixing the problems in your programs. It covers three topics:


1) How to get the PHP interpreter to report the errors that interest you.
2) How to locate basic syntax errors in your program.
3) How to check the values of variables as your program is running.

Configuring Error Reporting

First of all, you need to configure the PHP interpreter so that when an error happens, you can see information about it. The error info can be sent along with program output to the web browser. It can also be included in the web server error log. A common way to set things up is to have error output go to the web browser when you're debugging your program, and then to the web server error log once the program is finished and (supposedly) working properly. That way, web site users can't see any potentially sensitive data included with error output.

To make error messages display in the browser, set the display_errors configuration directive to On. To send errors to the web server error log, set log_errors to On. You can set them both to On if you want error messages in both places.
An error message that the PHP interpreter generates falls into one of five different categories:


Parse error: A problem with the syntax of your program, such as leaving a semicolon off of the end of a statement. The interpreter stops running your program when it encounters a parse error.

Fatal error: A severe problem with the content of your program, such as calling a function that hasn't been defined. The interpreter stops running your program when it encounters a fatal error.
Warning: An advisory from the interpreter that something is fishy in your program, but the interpreter can keep going. Using the wrong number of arguments when you call a function causes a warning.

Notice: A tip from the PHP interpreter, playing the role of Miss Manners. For example, printing a variable without first initializing it to some value generates a notice.

Strict notice: An admonishment from the PHP interpreter about your coding style. Most of these have to do with esoteric features that changed between PHP 4 and PHP 5, so you're not likely to run into them too much.

You don't have to be notified about all of the different error categories. The error_reporting configuration directive controls which kinds of errors the PHP interpreter reports. The default value for error_reporting is E_ALL & ~E_NOTICE & ~E_STRICT, which tells the interpreter to report all errors except notices and strict notices.

PHP defines some constants you can use to set the value of error_reporting so that only errors of certain types get reported: E_ALL (for all errors except strict notices), E_PARSE (parse errors), E_ERROR (fatal errors), E_WARNING (warnings), E_NOTICE (notices), and E_STRICT (strict notices).

Because strict notices are rare (and new to PHP 5), they are not included in E_ALL. To tell the PHP interpreter that you want to hear about everything that could possibly be an error, set error_reporting to E_ALL E_STRICT.

Fixing Parse Errors

The first time you write a PHP program, you discover that the PHP interpreter is extremely picky. If you leave out a necessary semicolon or start a string with a single quote but end it with a double quote, the interpreter doesn't run your program. It throws up its (virtual) hands, complains about a parse error, and leaves you stuck in the debugging wilderness.

This can be one of the most frustrating things about programming when you're getting started. Everything has to be phrased and punctuated just so in order for the PHP interpreter to accept it. One thing that helps this process along is writing your programs in an editor that is PHP-aware, such as BBEdit, Emacs, XEmacs, Komodo, Dreamweaver, PHPEd, PHPEdit, or Zend Studio.

These editors do syntax highlighting. This is a feature that changes the color of different parts of your program based on what those parts are. For example, strings are pink, keywords such as if and while are blue, comments are grey, and variables are black. Syntax highlighting makes it easier to detect things like a string that's missing its closing quote: the pink text continues past the line that the string is on, all the way to the end of the file (or to the next quote that appears later in the program).

Another feature of these editors is quote and bracket matching. This helps to make sure that your quotes and brackets are balanced. When you type a closing delimiter such as }, the editor highlights the opening { that it matches. Different editors do this in different ways, but typical methods are to flash the cursor at the location of the opening {, or bold the { } pair for a short time. This behavior is helpful for pairs of punctuation marks that go together: single and double quotes that delimit strings, parentheses, square brackets, and curly braces.

These editors also show the line numbers of your program files. When you get an error message from the PHP interpreter complaining about a parse error in line 35 in your program, you can focus on the right place to look for your error.
Parse errors happen when the PHP interpreter comes upon something unexpected in your program.

Consider this broken program:

Inspecting Program Data

Once you clear the parse error hurdle, you still may have some work to do before you reach the finish line. A program can be syntactically correct but logically flawed. Just as the sentence "The tugboat chewed apoplectically with six subtle buffaloes" is grammatically correct but meaningless nonsense, you can write a program that the PHP interpreter doesn't find any problems with, but doesn't do what you expect.
If your program is acting funny, add some checkpoints that display the values of variables. That way, you can see where the program's behavior diverges from your expectations. The following program incorrectly attempts to calculate the total cost of a few items:

Going Further

Once you've got error reporting set up as you like it, and you know how to find parse errors, and you can inspect program data, you're on your way to a fruitful debugging career. However, a fully fleshed-out PHP programmer's toolbox consists of much more than just the tips in this article. Chapter 12 of Learning PHP 5, "Debugging," includes some additional debugging techniques. For more advanced debugging possibilities, check out PHP extensions such as XDebug and apd. Some of the PHP-aware editors listed in this article also include integrated debugging capabilities.

3 Comments:

  • Your article is very helpful as I'm a newbie at PHP and am finding debugging to be the most frustrating part of the process. I'm curious though, you mention Dreamweaver as "an editor that is PHP-aware". I am currently using Dreamweaver 8 and can not find an error compiler for PHP. I have not seen an option for PHP in the "Validate Settings". Any suggestions?

    By Blogger Kandice, at 3:11 PM  

  • I find this article very useful because it gives just enough insight into PHP architecture and provides just enough info for somebody ho is relatively new to PHP to start debugging. But I think the emphasis can be made that you will be better off with good IDEs.
    I suggest NuSphere PhpED. David mentioned this PHP IDE in his post. It is made by NuSphere http://www.nusphere.com/products/index.htm( I am biased as I have working relationships with them, but trust me, I am the user of the product)
    NuSphere developed dbg - php debugger extension, similar in concept to XDebug mentioned in David's post and incorporated it in PhpED. Using it you can see how your script is executed, the values of the variables, arrays - everything basically.
    I am of opinion that you need to code in PHP IDE, not just php aware editor. While the argumnet can be made that you may gain more of php knowledge jumping through hoops of "row" php - I'd say that you'll get the same benefit by writing more code because of productivity increase.

    By Blogger mosc0411, at 4:16 AM  

  • Kandice,

    I don't have a lot of experience with the new dreamweaver.

    I personally use php designer 2006 for all of my development

    http://www.mpsoftware.dk/

    I did a little research and it seems a lot of people are having issues with the new dreamweaver and php.

    I found this on a deja.com article:

    "If you look on the bar that has:
    [<>] Code | [--] Split | [] Design
    you'll see a button right before "Title" that has a lightning bolt. That's "Live Preview". If you click that, it should run your PHP code for you automatically, or on refresh. Now, this will run all of your PHP code. It's probably not what you expect, but it's close!!"

    By Blogger justin silverton, at 8:36 PM  

Post a Comment

Links to this post:

Create a Link

<< Home