ξσ Dicky's Blog σξ

朋友多了,寂寞卻沒少,朋友沒有了你,得到了天下最高的技術又能如何?人類的全部才能無非是時間和耐心的混合物.---巴尔扎克

Traditional Chinese

导航

Debugging techniques for PHP programmers

Table of contents

Debugging techniques for PHP programmers

Using print statements, error reporting, and the PHPeclipse plug-in

Tyler Anderson recieved both his B.S. in Computer Science in 2004 and his M.S. in Electrical and Computer Engineering in 2005 from Brigham Young University. Tyler has written and coded numerous articles and tutorials for IBM developerWorks and DevX.

Summary: Explore various methods for debugging PHP applications, including turning on error reporting in Apache and PHP, and by placing strategic print statements to locate the source of more difficult bugs through a simple example PHP script. The PHPeclipse plug-in for Eclipse, a slick development environment with real-time syntax parsing abilities, will also be covered, as well as the DBG debugger extension for PHPeclipse.

Date: 29 Nov 2005
Level: Introductory
Activity: 36162 views

// // widget div id and article id as args //window.artRating.init('art-rating-widget'); //
capture_referrer();

Introduction

There are many PHP debugging techniques that can save you countless hours when coding. An effective but basic debugging technique is to simply turn on error reporting. Another slightly more advanced technique involves using print statements, which can help pinpoint more elusive bugs by displaying what is actually going onto the screen. PHPeclipse is an Eclipse plug-in that can highlight common syntax errors and can be used in conjunction with a debugger to set breakpoints.

Setting up

To learn the concepts described in this article, you are going to need PHP, a Web server, and Eclipse. The latest version of PHP supported by the debugger extension is V5.0.3.

We need a Web server to parse the pages you create in PHP and display them to the browser. This article uses Apache V2. However, any Web server will suffice.

To take advantage of some of the debugging techniques in this article, you need to install Eclipse V3.1.1 and the plug-in: PHPeclipse V1.1.8. Since Eclipse requires Java™ technology, you also need to download that.

You also need the debugger module extension for PHP. Installing it is a bit tricky. Carefully follow the instructions for installing the debugger extension. For now, comment out the lines where you are asked to load and configure the extension in PHP in the php.ini file. We’ll uncomment those lines when we’re ready to use the debugger.

See Resources for download information. Now let's move on to error messages.


Back to top

Error messages

Error messages are your first line of defense as a developer. You don't want to be developing code in PHP on a server that is not configured to display error messages. However, keep in mind that when your code is debugged and ready to go live, you want to make sure error reporting is turned off because you don't want visitors to your site seeing error messages that may give them enough knowledge to exploit a weakness and hack your site.

You can also use error messages to your advantage because they display the exact line of code that threw or generated an error. This makes debugging a matter of looking at the line number shown on the browser by the generated error and checking that line number in your code. Later, you will see that the PHPeclipse plug-in aides significantly in the development and debugging process by underlining syntax errors on the fly and by marking syntax errors with a red "x" when saving your file.

Let's take a look at how to turn error reporting on in the php.ini file and set the level of error reporting. Then you'll learn how to override these settings in the Apache configuration file.

Error reporting in PHP

There are many configuration settings in the php.ini file. You should already have set up up your php.ini file and placed it in the appropriate directory, as shown in the instructions in the Install PHP and Apache V2 on Linux document (see Resources). There are a couple configuration variables you should know about when debugging your PHP applications. Here they are with their default values:

display_errors = Off  error_reporting = E_ALL  

You can discover the current default values of these variables by searching for them in the php.ini file. The purpose of the display_errors variable is self-evident -- it tells PHP whether or not to display errors. The default value is Off. To make your life easier in the development process, however, set this value to On by replacing Off:

display_errors = On  

The error_reporting variable has a default value of E_ALL. This displays everything from bad coding practices to harmless notices to errors. E_ALL is a little too picky for my liking in the development process because it clutters the browser output by displaying notices on the screen for small things like uninitialized variables. I prefer to see the errors, any bad coding practices, but not the harmless notices. Therefore, replace the default value of error_reporting as follows:

error_reporting = E_ALL & ~E_NOTICE  

Restart Apache, and you're all set. Next, you'll learn how to do the same thing on Apache.

Error reporting in the server

Depending on what Apache is doing, turning error reporting on in PHP may not work because you may have multiple PHP versions on your computer. It's sometimes hard to tell which PHP version Apache is pointing to because Apache can only look at one php.ini file. Not knowing which php.ini file Apache is using to configure itself is a security problem. However, there is a way to configure PHP variables in Apache to guarantee the setting of the correct error levels.

Also, it's good to know how to set these configuration variables on the server side to veto or pre-empt the php.ini file, providing a greater level of security.

You should already have toyed with basic configurations in the http.conf file at <apache2-install-dir>/conf/httpd.conf when you configured Apache.

To do the same as you just did in the php.ini file, add the following lines to your httpd.conf to override any and all php.ini files:

php_flag  display_errors        on  php_value error_reporting       2039  

This overrides the flag you have set for display_errors in the php.ini file, as well as the value of error_reporting. The value 2039 stands for E_ALL & ~E_NOTICE. If you prefer E_ALL, set the value to 2047, instead. Again, make sure you restart Apache.

Next, we'll test error reporting on your server.

Testing error reporting

You will save a great deal of time if you leave error reporting enabled. Errors in PHP point you right to the error in your code. Create a simple PHP file, test.php, and define it as shown in Listing 1.


Listing 1. A simple PHP that generates an error
  <?php  print("The next line generates an error.<br>");  printaline("PLEASE?");  print("This will not be displayed due to the above error.");  ?>  

The first print() statement should display its contents to the Web browser. However, the second statement generates and displays an error to the Web page. This results in the last print() statement do nothing, as shown in Figure 1.


Figure 1. Generating an error
Generating an error

You have error reporting turned on! Next, we use print statements to help debug applications.


Back to top

Introducing print statements

Because functional bugs in your application don't generate errors, knowledge on how to accurately place and use print or die statements to debug your PHP application can be a great asset in your arsenal of debugging strategies. You can use print statements to narrow down the locations of problem statements in your code that may not be syntactically incorrect or bugs in the code, but they are bugs in the functionality of your code. These are the hardest bugs to find and debug because they throw no errors. You only know that what is being displayed to the browser isn't what you intended, or that what you thought was being stored in your database isn't being stored at all.

Suppose you are processing form data sent in via a GET request and want to display the information to the browser, but for whatever reason, the data is either not being submitted properly, or it isn't being read from the GET request properly. To debug such a problem, it's important to know what the value of the variable is, using a print() or a die() statement.

The die() statement halts program execution and displays text to the Web browser. The die() statement is particularly useful if you don't want to have to comment out your code, and you only want everything up to the error and the error displayed and nothing after.

Let's test this concept of using print statements in PHP.

Debugging using print statements

In my years as a programmer where I developed applications on Linux® boxes with no handy GUI to tell me where my bugs were, I quickly caught on that the more print statements I laced my program with the more chances I had of narrowing down the bugs in my application to a single line. Create another PHP file, test2.php, and define it as shown in Listing 2.


Listing 2. Display all variables submitted via GET
  <?php   $j = "";   print("Lets retrieve all the variables submitted to this ");   print("script via a GET request:<br>");   foreach($_GET as $key => $i){       print("$key=$j<br>");   }   if($_GET['Submit'] == "Send GET Request")       $j = "done!<br>";  ?>  <form method="GET">       Name: <input name="name"><br>       Email: <input name="email" size="25"><br>       <input name="Submit" type="submit" value="Send GET Request">  </form>  

You may be able to spot the bug in Listing 2 very easily. Good for you! Note that this is a simple script, and is shown as an example in using print statements to debug. The script simply takes all variables in the GET request, if any, and displays them back to the browser. A form is also supplied for you to send variables to the server using a GET request for testing. See the output, as shown in Figure 2.


Figure 2. Output of test2.php
Output of test2.php

Now click the Send GET Request button. Notice that only the keys of the $_GET request got displayed to the browser, and the correct values did not. You can place a print statement within the loop to verify that data indeed exists at each element in the foreach loop. See Listing 3.


Listing 3. Using a print statement to verify code functionality
  ...   foreach($_GET as $key => $i){       print("Correct data? " . $_GET[$key] . "<br>");       print("$key=$j<br>");   }  ...  

The placed print statement is in bold font. Notice that you already know that the displayed $key values on the Web browser are correct, but for some reason, the values aren't being displayed correctly. See the new output, as shown in Figure 3.


Figure 3. Output of modified test2.php
Output of modified test2.php

Now you know that your application is receiving the variables in the GET request correctly, so there must be a bug in your code. You look over and notice that the variable you are using for displaying the values, $j, is the wrong one. You specified $i in the foreach statement, which must have the correct values, but you accidentally typed in $j. You quickly fix the problem by replacing $j with $i and see the correct output by reloading the page, as shown in Figure 4.


Figure 4. Output of fixed test2.php
Output of fixed test2.php

You can now remove or comment out the print statement you added because you have discovered the bug in your code. Notice that this is a small subset of the many errors you might experience while debugging your application. A good solution to a problem you may encounter when working with a database is to print out your SQL statements to make sure that what you are executing SQL you intended to execute.

Now you'll take a look at using the Eclipse IDE and the PHPeclipse plug-in and debugger extension to further aid you in your debugging ventures.


Back to top

Using PHPeclipse

You have probably used Eclipse, but you aren't familiar with it. See Resources for introductions to the Eclipse platform.

The PHPeclipse plug-in for Eclipse is a popular tool used for developing PHP applications. Start Eclipse and specify your workspace directory as the www directory for Apache (c:\www on my machine). Now click on File > New > Project. The New Project wizard will pop up. Double-click on the PHP folder and select PHP Project. Click Next, enter a project name, debugArticle, and click Finish.

If you set up your Web server to listen to port 80, you don't need to change anything. Otherwise, go to the Navigator window and right-click on your PHP project, debugArticle. Select Properties, then click PHP Project Settings. Click Configure Workspace Settings and change localhost appropriately or add the port your Web server is listening on (http://localhost:8080, for example). Click Apply and you're set.

The Navigator Window should display your project and a single .project file. Right-click on your project as you did before, except this time select New > PHP File. Replace *.php with the name of the PHP file you want to create, test3.php, and click Finish. A new file should appear in the Eclipse IDE. You may have to navigate the bottom window to the PHP Browser to view the current output of your PHP file (see Figure 5).


Figure 5. The PHPeclipse plug-in for Eclipse
The PHPeclipse plug-in for Eclipse

Note that only Windows® users can use the PHP browser as shown in Listing 5. The exact same functionality can be used by opening up a separate browser window and pointing your browser to the directory where your test scripts are located.

Now let's demo this application and prove its awesome capabilities.

In the Using the debugger section, you will learn how to debug your PHP application using Eclipse, PHPeclipse and the debugger PHP extension downloaded earlier. You'll start by learning how to use its syntax parsing abilities.

Syntax parsing and underlining

Let's start by seeing how PHPeclipse provides you with real-time syntax parsing abilities to assist you with debugging PHP applications. To see this feature in action, start by defining the test3.php file in Eclipse, as shown below.

<?php  print(,"Hello World!");  ?>  

Notice that two characters underlined in Listing 4 get underlined in Eclipse, notifying you of incorrect syntax. Saving the file by pressing Ctrl+S displays the Parse error in Eclipse by placing a red "x" by the line that matches the parse error in your code, as shown in Figure 6.


Figure 6. Syntax error highlighting
Syntax error highlighting

Now let's demo the PHP browser. This window gives you a preview of the current PHP script, as shown in Figure 6.

Remove the comma (,) from test3.php, defined above. Save the file by pressing Ctrl+S, and watch the PHP browser window update by displaying Hello World (see Figure 7).


Figure 7. Previewing PHP scripts in PHPeclipse
Previewing PHP scripts in PHPeclipse

Next up is setting breakpoints in PHP using the debugger.


Back to top

Using the debugger

Using the debugger, you can set breakpoints and see the browser output from your PHP code up to the breakpoint you set. You can then resume code execution and see the rest of the browser output up to the next breakpoint and the next until your PHP script has completed.

Uncomment the lines you commented out in the php.ini file in the Setting up section and restart Apache. The debugger is loaded, and Eclipse will be able to hook into it.

Now let's set up the debug environment in Eclipse. Create a new test4.php file and leave it empty for now. Now click Run > Debug. Select PHP DBG Script on the left-side panel and click New. Now go to the File tab, and type in your current project, debugArticle, and the file you want to debug, test4.php. Now go to the Environment tab, then to the Interpreter subtab. Browse for your php.exe file in your PHP install directory (mine is c:\apps\php5.0.3\php.exe). Now click on the Remote Debug subtab, select Remote Debug, and if you're not using Windows, uncheck the "Open with DBGSession URL in internal Browser box." Set the Remote Source path equal to the absolute path (not the Web path) to the PHP script you're going to test (I have mine set to c:\www\debugArticle\test4.php). Now click Debug.

The Debug perspective should load, as shown in Figure 8. Otherwise, click Window > Open Perspective > Other, and select Debug.


Figure 8. Debug perspective in Eclipse
Debug perspective in Eclipse

Now you're ready to set breakpoints.

With the versions of the plug-in and extension used in this article, a breakpoint function is required because PHP buffers output before sending it to the browser. Besides that, you need to do more than set a breakpoint to flush the current display data to your Web browser, so define your test4.php file, as shown below and in Figure 8 above.


Listing 4. Setting and creating breakpoints
  <?php  function break-point(){      ob_flush();      flush();      sleep(.1);      debugBreak();  }  print("This will get shown first, ");  print("as will this<br>");  breakpoint();  print("This won't get shown until after ");  print("continuing the break-point<br>");  breakpoint();  print("END!");  ?  

The breakpoint() function flushes output buffered and any other buffered data to the Web browser. The call to sleep(.1) is necessary so the server has enough time to flush the data out to the Web browser before code execution is halted at debugBreak(), a function known internally to the PHP debugger extension you downloaded earlier. Thus, calling breakpoint() flushes data from HTML blocks, print() and echo() statements to the browser, then halts code execution.

After you have written the code shown in Listing 4, you can open a browser and point to test4.php or you can look at the PHP browser window (http://localhost/debugArticle/test4.php for me). Each time you type and save the file, the debugging sequence is already initiated in the PHP browser window. If you are not using Windows, look at test4.php through your browser. After saving your file, resume code execution with F8 or by clicking Run > Resume. Do this until you you see END! as the last line of output (see figures 9, 10 and 11).


Figure 9. Initial PHP browser output up to first breakpoint
Initial PHP browser output up to first breakpoint

Notice how the Debug window in Figure 9 shows the execution output as suspended.


Figure 10. PHP browser output after first breakpoint and before second breakpoint
PHP browser output after first breakpoint and before second breakpoint

The Debug window in Figure 10 still shows execution as suspended and the second set of data is shown in the PHP browser.


Figure 11. Full PHP browser output
Full PHP browser output

Notice that the code is no longer suspended in the Debug window in Figure 11, and the entire script has executed, as shown in the PHP browser of Figure 11.

Since you have witnessed the advantages of developing with PHPeclipse and the debugger extension, you'll wonder how you ever got along without it.


Back to top

Summary

Now that you have added the use of error reporting, print statements, PHPeclipse, and the debugger extension to your arsenal of debugging techniques in PHP, you will become a more effective PHP coder by reducing the number of errors you create per line of code. See Resources for some PHP tutorials on which to test your new skills.



Back to top

Download

Description Name Size Download method
Sample code for PHP debugging os-debugsource.zip 1.12KB HTTP

Information about download methods


Resources

Learn

Get products and technologies

  • Download the latest version of PHP from PHP.net.

  • Get the latest version of Apache V2.

  • Download Java technology from Sun Microsystems.

  • Get the latest version of Eclipse from Eclipse.org.

  • Download PHPeclipse from Sourceforge. Unzip Eclipse to eclipse-install-dir, then unzip PHPeclipse to eclipse-install-dir. Follow the PHPeclipse instructions when installing the extension. However, comment out the lines where you are asked to load and configure the extension in PHP in the php.ini file. You'll uncomment those lines when you're ready to use the debugger.

  • Order the SEK for Linux, a two-DVD set containing the latest IBM trial software for Linux from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.

  • Innovate your next open source development project with IBM trial software, available for download or on DVD.

Discuss

About the author

Tyler Anderson recieved both his B.S. in Computer Science in 2004 and his M.S. in Electrical and Computer Engineering in 2005 from Brigham Young University. Tyler has written and coded numerous articles and tutorials for IBM developerWorks and DevX.

posted on 2009-11-14 17:21  ξσ Dicky σξ  阅读(488)  评论(0编辑  收藏  举报