Debugging Summary of PHP Programmer

Source: Internet
Author: User
Tags configuration settings flushes parse error php debugger php print php programming
As you know, in the development process, the code is very important, debugging techniques for some common mistakes can help improve the efficiency of code writing.

This article describes various ways to debug a 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 basic debugging technique is to turn on error reporting. Another slightly more advanced technique, including the use of print statements, is to help pinpoint bugs that are more difficult to spot by displaying what actually appears on the screen. PHPEclipse is an Eclipse plugin that emphasizes common syntax errors that can be combined with the debugger for setting breakpoints.

Set up
To learn the concepts described in this article, PHP, WEB servers, and Eclipse are required. 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 Eclipse V3.1.1 and plug-in PHPEclipse V1.1.8. Because Eclipse requires Java technology, it also needs to be downloaded.
PHP's Debugger Extension module is also required. It's a little bit cumbersome to install. Follow the instructions for installing the debugger extensions carefully. Now, comment out the lines in the php.ini file that require the load and configuration of the PHP extension. When you need to use the debugger, uncomment it again.
See Resources for download information. The error message is now described.

Error message
The error message is the first line of defense as a developer. Nobody wants to develop code in PHP on a server that is not configured to display error messages. However, keep in mind that when the code is debugged and ready to run, you should make sure that you close the error report because you don't 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 black out the site.
You can also serve yourself with error messages because they display the correct line of code that throws or generates an error. In this way, debugging becomes the line number displayed in the browser to view the generated error, and the line is checked in the code. Later, you'll see that the PHPEclipse plugin provides great help during development and debugging by instantly underlining syntax errors and labeling syntax errors with red "X" when saving a file.
Let's start by looking 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 your own php.ini file set up and put it in the appropriate directory, as shown in the documentation for installing 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 the 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 both 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, please set this value to on:

Copy the Code code as follows:

Display_errors = On


The default value for the error_reporting variable is e_all. This setting shows all the information from bad coding practices to harmless prompts to errors. E_all is a bit too thin for the development process because it shows hints on the screen for small things (such as uninitialized variables), which 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 the 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 an error report in PHP may not work because there may be multiple versions of PHP on your computer. It is sometimes difficult to tell which PHP version Apache is using because Apache can only view one php.ini file. It is a security issue to not know 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 level of error is set.
Also, it is 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 been exposed to the basic configuration in the http.conf file in <apache2-install-dir>/conf/httpd.conf.
To do what has already been done in the php.ini file, add the following lines to httpd.conf, overwriting any php.ini files:

Copy the Code code as follows:

Php_flag display_errors on Php_value error_reporting 2039


This overrides the flags already set for display_errors in the php.ini file, as well as the value of error_reporting. A value of 2039 represents E_all & ~e_notice. If you prefer to use E_all, set the value to 2047. Again, you'll restart Apache.
Next, you will test the error report on the server.
Test Error Report
If you start an error report, you save a lot of time. Errors in PHP can 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 the Code code as follows:

<?php print ("The next line generates an error.<br>"); Printaline ("please?"); Print ("This is not being displayed due to the above error."); ?>


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

The error report is now open! Next, 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, in all debugging strategies, knowledge about how to properly place and use print or Die statements to debug a PHP application is a good asset. You can use the print statement to narrow down the problem statements in your code, which are syntactically error-free and not a bug, but from the functionality of the code. These are the hardest bugs to find and debug because they don't throw errors. The only thing you know is that the content displayed on the browser is not what you want, or what you want to save in the database is not saved at all.
Suppose you are processing form data sent over a GET request and want to display information to the browser, but for some reason the data is not committed correctly, or it cannot be read correctly from the GET request. To debug such problems, it is important to use the print () or Die () statement to know what the value of the variable is.
The die () statement aborts program execution and displays text on the Web browser. The die () statement is particularly useful if you do not want to comment out the code and want to display only the information and error messages that precede the error and do not want to display the following information.
Let's test the concept in PHP with the print statement
Debugging with the print statement
When I was a programmer, when I was developing an application on Linux, there was no convenient GUI to tell me where the bug was, and I quickly discovered that the more print statements I put in the program, the greater the chance that I would narrow the range of bugs to one line in the application. Please create another PHP file, test2.php, and define it as shown in Listing 2.

Listing 2. Show all variables submitted via GET

Copy the Code code as follows:

<?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 find it very easy to discover the bug! in Listing 2 You're great! Note, however, that this is a very simple script, just an example of how to debug with the print statement. This script simply extracts all the variables in the GET request, and if so, displays them on the browser. A form is also provided that sends a variable to the server for testing with a GET request. Look at the output, shown in 2.
Figure 2. Output of the test2.php

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

Copy the Code code as follows:

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


The print statement that 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. Take a look at the new output, shown in 3.
Figure 3. The output of the modified test2.php

Now that the application has correctly received the variable from the GET request, there must be a bug in the code. After viewing, it is noted that the variable used to display the value $j is wrong. specified in the foreach statement $i , so it will certainly have the correct value, but inadvertently entered $j . So by $j replacing it, $i quickly correcting the error, re-loading the page, we see the correct output, as shown in 4.


Figure 4. Corrected output of the test2.php

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

Now it's time to look at how to use the Eclipse IDE and PHPEclipse plug-ins and debugger extensions to further assist in 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 plugin for Eclipse is a popular tool for developing PHP applications. Please start Eclipse and designate the workspace directory as the WWW directory for Apache (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 modifications. 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 then modify the appropriate localhost or add the port on which the Web server listens (for example, http://localhost:8080). Click Apply to complete the setup.

The Navigator window should display the project and a. project file. Right-click on the project, as you did earlier, just choose New > PHP Filethis time. Replace *.php with the name of the PHP file you want to create test3.php, and then click Finish. 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 a standalone browser window and pointing your browser to the directory where the test script is located.

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 debugger PHP extensions that you downloaded earlier. Start by learning how to use its syntax parsing capabilities.

Parsing and underlining syntax

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


<?phpprint (, "Hello world!");? >


Note that the two characters underlined in Listing 4 are underlined in Eclipse, suggesting that the syntax is incorrect. Pressing ctrl+s to save the file shows a parse error in Eclipse: The line in the code corresponding to the parse error is prefixed with the red "X", which is shown in 6.


Figure 6. Syntax error highlighting

Now demonstrate the PHP browser. This window provides a preview of the current PHP script, as shown in 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 proceed with the execution of the code and view the browser output before the next breakpoint, and then to the next until the PHP script finishes.

Now uncomment the lines commented out in php.ini in the "Settings" section and restart Apache. Now that the debugger is loaded, Eclipse can hang with 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 PHP DBG Script in the left panel and click New. Now go to the File tab, enter the current project debugarticle and the file test4.phpyou want to debug. Now go to the Environment tab, and then to the interpreter sub tab. Locate the Php.exe file (mine is C:\apps\php5.0.3\php.exe) in the PHP installation directory. Now click the Remote Debug Sub-tab and select Remote Debug, if you are not using Windows, cancel the Open with dbgsession URL in Internal browser 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 settings are c:\www\debugArticle\test4.php). Now click Debug.

The Debug perspective should now be loaded, as shown in 8. Otherwise, click Window > Open perspective >Other and select Debug.


Figure 8. Debug Perspective in Eclipse

You can now set a breakpoint.

The breakpoint feature is required for the plug-in and extended versions used in this article, because PHP buffers the output before it sends it to the browser. Beyond that, 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

<?phpfunction Break-point () {  ob_flush ();  Flush ();  Sleep (. 1);  DebugBreak ();} Print ("This would get shown first,");p rint ("as would this<br>"); Breakpoint ();p rint ("This won ' t get shown until after ");p rint (" continuing the break-point<br> "); Breakpoint ();p rint (" end! ");?


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

After writing the code like 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 through your browser. After you save the file, use F8 or click Run > Resume to continue the code execution. Continue to do so until the last line of output is END! reached (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 execution as pending.


Figure 10. PHP Browser output before the first breakpoint to 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 in Figure 11 is no longer suspended, the entire script has been executed, and the PHP browser in 11 shows.

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

Conclusion

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

Download Sample code for PHP debugging

Resources

Learn

  • You can refer to the original English text on the DeveloperWorks global site in this article.

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

  • Please visit eclipse.org for full information on programming and how to use it.

  • "Getting Started with Eclipse platform " (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. Please read this tutorial on Installing and configuring the debugger .

  • To learn more about Eclipse, please visit DeveloperWorks's Eclipse Project Resources.

  • To learn more about PHP, please visit DeveloperWorks's PHP project Resources.

  • Please refer to 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 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 a wealth of how-to information, tools, and project updates to help you develop with open source technology and use them with IBM products.


Access to products and technologies

    • 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 unzip PHPEclipse to Eclipse-install-dir. When installing an extension, follow phpeclipse instructions. However, comment out those lines where you want the PHP extension to be loaded and configured in the php.ini file. Uncomment these lines when you are ready to use the debugger.

    • Order a free SEK for Linuxset of DVDs (two photos) with the latest IBM trial software for Linux from DB2, Lotus, Rational, Tivoli, and WebSphere.

    • Please use IBM trial software to retrofit your next open source development project, which can be downloaded or made 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. It is 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 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.