Debugging Techniques for PHP Programmers summary _php tips

Source: Internet
Author: User
Tags configuration settings flush flushes parse error php debugger php programming php script advantage

This article describes various ways to debug your PHP application, including opening error reports in Apache and PHP, and finding the source of more difficult bugs by placing a strategic print statement in a simple PHP script. It also introduces the PHPEclipse plug-in for Eclipse, a flexible development environment with real-time parsing capabilities and an introduction to PHPEclipse's DBG debugger extensions.
Brief introduction
There are many PHP debugging techniques that can save a lot of time when coding. An effective but very basic debugging technique is to turn on error reporting. Another slightly more advanced technique involves using print statements to help pinpoint bugs that are more difficult to find by displaying what actually appears on the screen. PHPEclipse is an Eclipse plug-in that can emphasize common syntax errors that can be combined with the debugger to set breakpoints.

Set up
To learn the concepts described in this article, you need PHP, WEB servers, and Eclipse. The PHP version supported by the debugger extension is V5.0.3.
We need a WEB server to parse the pages created in PHP and display them to the browser. The Apache2 is used in this article. However, any WEB server can meet the requirements.
To take advantage of some of the debugging techniques described in this article, you need to install the Eclipse V3.1.1 and plug-in PHPEclipse V1.1.8. Because Eclipse requires Java™ technology, download it as well.
You also need a debugger extension module for PHP. It's a little bit cumbersome to install it. Follow the instructions for installing the debugger extensions carefully. Now, first comment out the rows in the php.ini file that require loading and configuring the PHP extension. When you need to use the debugger, uncomment it again.
See Resources for download information. Now let's introduce the error message.

Error message
An error message is the first line of defense for developers. No one wants to use PHP to develop code on a server that is not configured to display error messages. However, keep in mind that when code debugging is complete and ready to run, you should make sure that error reporting is turned off because you do not want the site's visitors to see the error message because it gives them enough information to take advantage of the site's weaknesses and hack the site down.
You can also use error messages to serve yourself because they display the correct line of code that throws or generates errors. In this way, debugging becomes the line number that is displayed on the browser to see the generated error, and the line is checked in code. Later on, you'll see that the PHPEclipse plug-in can provide great help during development and debugging by underlining syntax errors in an instant and using a red "x" notation for syntax errors when saving files.
Let's look at how to turn on Error reporting in the php.ini file and set the level of error reporting. You will then learn how to override these settings in the Apache configuration file.
Error reporting for PHP
There are many configuration settings in the php.ini file. You should have set up your own php.ini file and put it in the appropriate directory, as shown in the documentation for PHP and Apache 2 on Linux (see Resources). When debugging a PHP application, you should know two configuration variables. The following are the two variables and their default values:

Copy Code code as follows:

Display_errors = Off
error_reporting = E_all

By searching for them in the php.ini file, you can find the current default values for these two variables. The purpose of the display_errors variable is obvious-it tells PHP if it shows an error. The default value is off. However, to make the development process easier, set this value to on:
Copy Code code as follows:

Display_errors = On

The default value for the error_reporting variable is e_all. This setting displays all information from bad coding practices to harmless hints to errors. E_all is a bit too thin for the development process because it displays hints on the screen for trivial things, such as variable initialization, and can mess up the browser's output. I just want to see errors and bad coding practices, but don't want to see harmless hints. Therefore, replace the default value of error_reporting with the following values:
Copy Code code as follows:

error_reporting = E_all & ~e_notice

Restart Apache, and it's all set up. Next, you'll learn how to do the same thing on Apache.
Error reporting on the server
Depending on what Apache is doing, opening the error report in PHP may not work because there may be multiple versions of PHP on the computer. Sometimes it's hard to tell which PHP version the Apache is using, because Apache can only view one php.ini file. It is a security issue not knowing which php.ini file Apache is using to configure itself. However, there is a way to configure PHP variables in Apache to ensure that the correct error level is set.
Also, it's best to know how to set these configuration variables on the server side to veto or preempt php.ini files, providing a higher level of security.
When you configure Apache, you should have contacted the basic configuration in the http.conf file in <apache2-install-dir>/conf/httpd.conf.
To do what you've done in the php.ini file, add the following lines to httpd.conf, overwriting any php.ini files:
Copy Code code as follows:

Php_flag display_errors on
Php_value error_reporting 2039

This overrides the flag already set for display_errors in the php.ini file, and the error_reporting value. The value 2039 represents E_all & ~e_notice. If you prefer to use E_all, set the value to 2047. Again, restart Apache.
Next, you will test the error report on the server.
Test Error Reporting
If you start error reporting, you save a lot of time. Errors in PHP point to errors in your code. Please create a simple PHP file test.php and define it as shown in Listing 1.
Listing 1. A simple PHP that generates errors
Copy Code code as follows:

<?php
Print ("The next line generates an error.<br>");
Printaline ("please?");
Print ("This won't be displayed due to the above error.");
?>

The first print () statement displays its contents to the Web browser. However, the second statement generates an error and is displayed on the Web page. This causes the last print () statement to not work, as shown in Figure 1.
Figure 1. Build Error

The error report is now turned on! Next, you use the PRINT statement to help debug your application.
Introducing the PRINT statement
Because a functional bug in an application does not produce an error, it is a good asset to have knowledge about how to correctly place and use print or Die statements to debug a PHP application in all debugging strategies. You can use the print statement to narrow the positioning of the problem statements in your code, which are syntactically correct and not a bug, but are a bug in terms of the functionality of your code. These are the most difficult bugs to discover and debug because they do not throw errors. The only thing to know is that the content that is displayed on the browser is not what you want, or the content you want to keep in the database is not saved at all.
Suppose you are processing a form data sent over a GET request and want to display the information to the browser, but for some reason, the data is not submitted correctly, or it cannot be read correctly from the GET request. To debug such a problem, it is important to use the print () or Die () statement to know what the value of the variable is.
The die () statement aborts the execution of the program and displays the text on the Web browser. The die () statement is particularly useful if you do not want to comment out the code, and you want to display only the information and error messages before the error, and do not want to display the following information.
Let's test this concept in PHP with the print statement.
Debugging with the print statement
When I was a programmer, when I developed an application on linux®, there was no convenient GUI to tell me where the bug was, and I quickly found that the more print statements I put in the program, the more I had the chance to narrow the range of bugs in my application. Please create another PHP file test2.php and define it as shown in Listing 2.

Listing 2. Show all variables submitted through get

Copy Code code as follows:

<?php
$j = "";
Print ("Lets retrieve all of 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= "><br>"
<input name= "Submit" type= "Submit" value= "Send get Request" >
</form>

You may find it very easy to see the bug! in Listing 2 You're great! Note, however, that this is a very simple script, just as an example of a demo that uses the print statement for debugging. This script simply extracts all the variables from the GET request, and if so, displays them on the browser. A form is also provided to send a variable to the server with a GET request for testing. See the output, as shown in Figure 2.
Fig. 2. Output of test2.php

Now click the Send Get Request button, and note that only the requested key appears on the browser and the $_GET correct values are not displayed. You can place a print statement in a loop to verify that foreach data is actually present in each element in the loop. See Listing 3.
Listing 3. Verifying the functionality of your code with the print statement

Copy Code code as follows:

...
foreach ($_get as $key => $i) {
Print ("Correct data?". $_get[$key]. "<br>");
Print ("$key = $j <br>");
}
...

The print statement you put in is bold. Note that the $key values displayed on the Web browser are now known to be correct, but for some reason the values are not displayed correctly. See the new output, as shown in Figure 3.
Figure 3-Modified test2.php output

Now that the application has correctly GET received the variable from the request, there must be a bug in the code. After viewing, note that the variable used to display the value $j is incorrect. specified in the foreach statement $i , so it must have the correct value, but inadvertently entered $j . So by putting the $j substitution into $i , quickly correcting the error, reload the page, you see the correct output, as shown in Figure 4.


Figure 4. Corrected output of the test2.php

You can now delete or comment out the print statement that you just added, because bugs in your code have been found. Note that this is just a small subset of many of the errors that you might encounter while debugging your application. A good solution for problems that you might encounter when working with a database is to output SQL statements to make sure that the SQL you execute is what you want to do.

Now let's see how you can use the Eclipse IDE and phpeclipse plug-ins and debugger extensions to further help with the debugging process.

Using PHPEclipse

You may have used Eclipse, but you may not be familiar with it. See Resources for an introduction to the Eclipse platform.

The PHPEclipse plug-in for Eclipse is a popular tool for developing PHP applications. Please start Eclipse and designate the workspace directory as Apache's www directory (c:\www on my machine). Now click File > New > Project. The New Project Wizard pops up. Double-click the php folder and select PHP Project. Click Next, enter the project name Debugarticle, and click Finish.

If you set the WEB server to listen on port 80, you do not need to make any changes. Otherwise, go to the Navigator window, right-click on the PHP project debugarticle , select Properties, and then click PHP Project Settings. Click Configure Workspace Settings and modify the appropriate localhost or add a port on which the Web server listens (for example, http://localhost:8080). Click Apply to complete the setup.

The Navigator window should display a project and a. project file. Right-click on the item, just like you did earlier, but this time, select New > PHP File. Replace *.php with the name of the PHP file you want to create, and then click Finishtest3.php. A new file should appear in the Eclipse IDE. You may need to navigate to the Php browser at the bottom of the window to view the current output of the PHP file (see Figure 5).


Figure 5. Eclipse's PHPEclipse Plugin

Note that only Windows® users can use the PHP browser as shown in Listing 5. You can also use the same functionality by opening the standalone browser window and pointing the browser to the directory where the test script resides.

Now to demonstrate this application, prove its power.

In the "Using the Debugger" section, you will learn how to debug your PHP application with Eclipse, PHPEclipse, and the previously downloaded debugger PHP extensions. Start by learning how to use its syntax parsing function.

Syntax parsing and underlining

Start by looking at how PHPEclipse provides the ability to help debug the real-time parsing of your PHP application. To see the actual application of this feature, start by defining test3.php in Eclipse as follows.

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

Note that the two characters underlined in Listing 4 are underlined in Eclipse, prompting the syntax to be incorrect. Pressing ctrl+s to save the file displays a parse error in Eclipse: The line that corresponds to parsing the error in your code will be marked with a red "X", as shown in Figure 6.


Figure 6. Grammatical errors emphasize

Now demo PHP Browser. This window provides a preview of the current PHP script, as shown in Figure 6.

Remove the comma () from the test3.php defined above , . Press Ctrl+s to save the file, and then watch the PHP browser window update to show Hello World (see Figure 7).


Figure 7. Previewing PHP scripts in PHPEclipse

The following is a breakpoint set in PHP with the debugger.

Using the debugger

Using the debugger, you can set breakpoints and view the browser output of your PHP code before the breakpoint you set. You can then continue executing the code and view the browser output before the next breakpoint, and then to the next until the PHP script completes.

Now uncomment the line that is commented out in php.ini in the "Settings" section and restart Apache. Now that the debugger is loaded, Eclipse can hang on to it.

Now design the debugging environment in Eclipse. Please create a new test4.php file and leave it blank first. Now click Run > Debug. Select the PHP DBG Script in the left panel and click New. Now go to the File tab and enter the current project debugarticle and the file test4.phpyou want to debug. Now go to the Environment tab, and then to the interpreter tab. Locate the Php.exe file in the PHP installation directory (mine is C:\apps\php5.0.3\php.exe). Now click the Remote Debug Sub tab and select Remote Debug, if you are not using Windows, cancel the Open with Dbgsession URLs in internal browse R box checkbox. Set the Remote Source path to be the same as the absolute path (not the Web path) of the PHP script you want to test (my setup is c:\www\debugArticle\test4.php). Now click Debug.

You should now mount the Debug perspective, as shown in Figure 8. Otherwise, click Window > Open perspective >Other, and select Debug.


Figure 8. Debug Perspective in Eclipse

You can now set a breakpoint.

For the Plug-ins and extensions used in this article, the breakpoint feature is required because PHP buffers the output before it is sent to the browser. In addition, you need to do more than just set a breakpoint to refresh the current display data to a Web browser, so define test4.php as shown below and in Figure 8.


Listing 4. Setting and creating breakpoints

<?php
function Break-point () {
  ob_flush ();
  Flush ();
  Sleep (. 1);
  DebugBreak ();
}
Print ("This'll get shown a");
Print ("as would this<br>");
Breakpoint ();
Print ("This won ' t get shown until");
Print ("Continuing the break-point<br>");
Breakpoint ();
Print ("end!");
?

breakpoint()The function flushes the buffered output and other buffered data to the Web browser. The sleep(.1) call is required so that the code is aborted debugBreak() before the server has enough time to flush the data to the Web browser, which is the internal function of the PHP debugger extension that was previously downloaded. In this way, the call breakpoint() flushes the HTML blocks, print() and echo() the statements ' data to the browser, and then aborts the code execution.

After writing the code as in Listing 4, you can open the browser and point to test4.php, or you can view the php browser window (mine is http://localhost/debugArticle/test4.php). Each time you enter and save a file, the debug sequence is started in the PHP browser window. If you are not using Windows, view test4.php from the browser. After you save the file, continue the code execution with F8 or click Run > Resume . Continue to do this until the last line of output is so END! far (see Figures 9, 10, and 11).


Figure 9. Initial PHP browser output to the first breakpoint

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


Figure 10. PHP Browser Output After the first breakpoint before the second breakpoint

The Debug window in Figure 10 still shows execution as pending, while the second set of data is displayed in the PHP browser.


Figure 11. Full PHP Browser output

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

Now that you've seen the advantage of developing with phpeclipse and debugger extensions, it's hard to imagine what it would be like without it.

Conclusion

Now that you've added error reporting, print statements, PHPEclipse, and debugger extensions to the debugging techniques of PHP, you can become a more efficient PHP coder by reducing the number of errors per line of code. See Resources for some of the PHP tutorials you can use to test these new skills.

Download Sample code for PHP debugging

Resources

Learn

  • You can refer to the English version of this article at the DeveloperWorks Global site.

  • Learn how to install Javaon windows-based and UNIX® systems.

  • Visit eclipse.org for complete information on programming and how to use it.

  • TheEclipse Platform Primer (developerworks,2002 November) provides a history and overview of Eclipse, including details on how to install Eclipse and plug-ins.

  • Please visit phpeclipse to learn more about installing phpeclipse and how to use it.

  • DBG is a full-featured PHP debugger engine, an interactive tool that helps debug PHP scripts. Read this tutorial on Installing and configuring the debugger .

  • To learn more about Eclipse, visit DeveloperWorks's Eclipse Projectresources.

  • To learn more about PHP, visit DeveloperWorks's PHP projectresources.

  • See the PHP Manual for more information on Error Reporting .

  • Please read the instructions for installing PHP and Apache2 on Linux .

  • Please read the instructions for installing the PHP and Apache2 on Windows .

  • To get a series of developerWorks tutorials for learning PHP programming, see " Learning PHP, part 1th ", learning PHP, part 2nd , and learning PHP, part 3rd .

  • Please pay close attention to DeveloperWorks technical events and Webcasts.

  • Visit the DeveloperWorks Open source zone for rich how-to information, tools, and project updates to help develop and use open source technology for IBM products.


Access to products and technology

    • Please download the latest version of PHPfrom Php.net.

    • Please download the latest version of Apache 2.

    • Please download Java technology from Sun company.

    • Please download the latest version of Eclipsefrom eclipse.org.

    • Please download phpeclipsefrom Sourceforge. Extract Eclipse to Eclipse-install-dir, then extract PHPEclipse to Eclipse-install-dir. When you install the extension, follow the phpeclipse instructions. However, comment out those lines where you want the PHP extensions to be loaded and configured in the php.ini file. Uncomment the lines when you are ready to use the debugger.

    • order free SEK for Linux, a DVD (two) that contains the latest IBM trial software for Linux from db2®, Lotus®, rational®, tivoli®, and websphere®.

    • Please use the IBM trial software to transform your next open source development project, which can be downloaded or available on DVD.


Discuss

    • Join the DeveloperWorks community by participating in DeveloperWorks blogs .



About the author

Tyler Anderson graduated from Brigham Young University in 2004 and received a degree in computer science. He is now his last semester as a master of computer engineering. In the past, he worked as a database programmer for dpmg.com, and now he is an engineer at the Stexar company in Beaverton, Ore.

Original Address http://www.ibm.com/developerworks/cn/opensource/os-debug/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.