Summary of debugging technology for PHP programmers

Source: Internet
Author: User
Tags php debugger

This article describes how to debug PHP applications.ProgramVarious methods, including opening error reports in Apache and PHP, and finding the source of a more difficult bug by placing strategic print statements in a simple PHP script. The phpeclipse plug-in for eclipse is also introduced. This is a flexible development environment with real-time Syntax Parsing capabilities. The dbg debugger extension for phpeclipse is also introduced.
Introduction
Many PHP debugging technologies can save a lot of time in coding. An effective but Basic Debugging Technique is to open an error report. Another slightly more advanced technique involves the use of print statements to help precisely identify more difficult bugs by actually appearing on the screen. Phpeclipse is an Eclipse plug-in that can emphasize common syntax errors and can be used with the debugger to set breakpoints.

Set
To learn the concepts described in this article, PHP, Web server, 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 with PHP and display them to the browser. Apache2 is used in this article. However, any web server can meet the requirements.
To use some Debugging techniques described in this article, you need to install eclipse v3.1.1 and phpeclipse v1.1.8. Because eclipse requires Java technology, you need to download it.
You also need the PHP debugger extension module. Installing it is a little troublesome. Follow the instructions for installing the debugger extension carefully. Now, comment out the lines that require loading and configuring PHP extensions in the PHP. ini file. Cancel the comment when you need to use the debugger.
See references for download information. This section describes error messages.

Error Message
Error messages are the first line of defense for developers. No one wants to use PHP for development on a server that is not configured to Display error messages.Code. However, remember that when the Code debugging is complete and you are ready to run it, make sure that the error report is disabled because you do not want the site visitors to see the error message, this will give them enough information to take advantage of the site's vulnerabilities and hack the site.
You can also use error messages to serve yourself, because they will display the correct code lines that throw or generate errors. In this way, debugging becomes to view the row number of the generated error in the browser, and check this line in the code. Later, you will see the phpeclipse plug-in instantly underline the syntax error and mark the syntax error with the red "X" when saving the file, it can be of great help in the development and debugging process.
First, let's take a look at how to enable the Error Report in the PHP. ini file and set the error report level. Then we will learn how to overwrite these settings in the Apache configuration file.
PHP Error Report
The PHP. ini file contains many configuration settings. You should have set your php. INI file and place it in the appropriate directory, as shown in instructions for installing PHP and Apache 2 on Linux (see references ). When debugging a PHP application, you should know two configuration variables. The two variables and their default values are as follows:

Copy code The Code is as follows: display_errors = off
Error_reporting = e_all

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

The default value of error_reporting variable is e_all. This setting displays all information from poor coding practices to harmless prompts to errors. E_all is a little too detailed for the development process, because it displays a prompt on the screen for some trivial matters (for example, the variable is not initialized), it will mess up the browser output. I only want to see errors and bad code practices, but do not want to see harmless prompts. Therefore, replace the default value of error_reporting with the following values:Copy codeThe Code is as follows: error_reporting = e_all &~ E_notice

restart Apache and set all the settings. Next, we will learn how to do the same thing on Apache.
the Error Report on the server
depends on the work being done by Apache. Opening the error report in PHP may not work because multiple PHP versions may exist on the computer. Sometimes it is difficult to tell which PHP version Apache is using, because Apache can only view one PHP. ini file. I don't know which PHP. ini file Apache is using to configure itself as a security issue. However, there is a way to configure the PHP variable in Apache to ensure that the correct error level is set.
In addition, it is better to know how to set these configuration variables on the server side to deny or preemptible the PHP. ini file to provide higher-level security.
you have been in touch with the basic configuration in the HTTP. conf file in /CONF/httpd. conf when configuring Apache.
in PHP. add the following lines to httpd. conf, overwrite any PHP. INI file: copy Code the code is as follows: php_flag display_errors on
php_value error_reporting 2039

This overwrites the flag set for display_errors and the value of error_reporting in the PHP. ini file. The value 2039 represents e_all &~ E_notice. If you want to use e_all, set the value to 2047. Similarly, restart Apache.
Next, test the Error Report on the server.
Test Error Report
If an error report is started, it will save a lot of time. Errors in PHP point to errors in the code. Create a simple PHP file test. php and define it as shown in Listing 1.
Listing 1. A simple PHP with incorrect generationCopy codeThe Code is as follows: <? 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 will display its content to the Web browser. However, the second statement will generate an error and display it on the web page. This makes the last print () Statement ineffective, as shown in 1.
Figure 1. Generation Error

The error report is now enabled! Next, use the print statement to debug the application.
Introduction to print statements
Because functional bugs in applications do not produce errors, in all debugging policies, knowledge about how to correctly place and use print or die statements to debug PHP applications is a good asset. You can use print statements to narrow down the problem statement positioning in the Code. These statements have no syntax errors or bugs, but they are bugs in the code function. These are the most difficult bugs to discover and debug, because they do not throw errors. The only thing you know is that the content displayed on the browser is not what you want, or the content you want to save in the database is not saved at all.
Assume that you are processing the form data sent through the GET request and want to display the information to the browser. However, for some reason, the data is not submitted correctly or cannot be correctly read from the GET request. To debug this type of problem, it is important to use print () or die () statements to know the value of the variable.
The die () Statement terminates program execution and displays text in a web browser. If you do not want to comment out the code, and only want to display the information before and after the error, then the die () Statement is particularly useful.
Let's use the print statement in PHP to test this concept.
Debug 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, I quickly found that the more print statements I put in the program, the more chance I will narrow the bug scope to a row in the application. Create another PHP file test2.php and define it as shown in Listing 2.

Listing 2. Show all variables submitted through get

Copy code The Code is 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 easily find bugs in Listing 2! You are great! However, please note that this is a very simple script, just as an example of Debugging Using the print statement. This script only extracts all the variables in the GET request. If so, it will display them in the browser. A form is provided to send a variable to the server with a GET request for testing. See output, 2.
Figure 2. Output of test2.php

ClickSend GET requestButton, note that only$ _ GetThe requested key is displayed in the browser, but the correct value is not displayed. You can put a print statement in the loop to checkForeachWhether data exists in each element of the loop. See listing 3.
Listing 3. Using the print statement to verify the code Function

Copy code The Code is as follows :...
Foreach ($ _ get as $ key => $ I ){
Print ("correct data? ". $ _ Get [$ key]." <br> ");
Print ("$ key = $ j <br> ");
}
...

The print statement is in bold. Note that the $ key value displayed on the web browser is correct, but for some reason, the value is not correctly displayed. See the new output, as shown in 3.
Figure 3. Output of test2.php after modification

Now you know that the application is correctlyGetWhen the request receives a variable, it must have a bug in the code. Check the variable used to display the value.$ JYes. InForeachThe statement specifies$ ISo it will certainly have the correct value, but it is not intended to be entered$ J. Therefore$ JReplace$ IThe error is corrected quickly. After the page is reloaded, the correct output is displayed, as shown in figure 4.

Figure 4. Corrected output of test2.php

Now you can delete or comment out the print statement you just added, because a bug in the code has been found. Note that this is only a small subset of the many errors that may be encountered during application debugging. A good solution for problems that may occur when you use the database is to output SQL statements to ensure that the executed SQL statements are what you want to execute.

Now let's take a look at how to use Eclipse IDE and phpeclipse plug-ins and debugger extensions to further help in the debugging process.

Use phpeclipse

You may have used eclipse, but may not be familiar with it. See references for an introduction to the eclipse platform.

The phpeclipse plug-in for eclipse is a popular tool used to develop PHP applications. Start eclipse and specify the workspace directory as the WWW directory of Apache (C: \ www on my machine ). ClickFile> New> Project. The new project wizard is displayed. Double-click the PHP folder and select the PHP project. ClickNext, Enter the project name debugarticle, and clickFinish.

If you set the Web server to listen on port 80, no modification is required. Otherwise, go to the Navigator window, in the PHP ProjectDebugarticleRight-click, select properties, and clickPHP Project Settings. ClickConfigure workspace settingsThen modify the appropriate localhost or add the Web server listening port (for example, http: // localhost: 8080 ). ClickApplyComplete the settings.

The Navigator window should display a project and A. project file. Right-click the project, as shown in the previous step.New> PHP File. Replace *. php with the name of the PHP file you want to create, and then clickFinish. A new file should appear in 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 phpeclipse plug-in

Note that only Windows users can use the PHP browser as shown in listing 5. You can also use the same function by opening the independent browser window and directing the browser to the directory where the test script is located.

Now let's demonstrate this application to prove its strength.

In the "use Debugger" section, you will learn how to use eclipse, phpeclipse, and the previously downloaded debugger PHP extension to debug PHP applications. First, learn how to use its syntax parsing function.

Syntax Parsing and underline

First, check how phpeclipse can help debug the Real-Time Syntax Parsing function of PHP applications. Depending on the actual application of this feature, first define test3.php in eclipse, as shown below.

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

Note that the two characters underlined in Listing 4 are underlined in eclipse, prompting that the syntax is incorrect. PressCTRL + SSave the file and a parsing error will be displayed in Eclipse: red "X" will be added to the line corresponding to the parsing error in the code, as shown in 6.

Figure 6. syntax error emphasis

Now we will demonstrate the PHP browser. This window provides a preview of the current PHP script, as shown in 6.

Delete the comma (,). PressCTRL + SSave the file, observe the updates in the PHP browser window, and display Hello world (see figure 7 ).

Figure 7. preview the PHP script in phpeclipse

The following describes how to use a debugger to set breakpoints in PHP.

Use the debugger

With the debugger, you can set breakpoints and view the browser output before the PHP code is set to the breakpoint. Then, you can continue code execution and view the browser output before the next breakpoint, and then go to the next one until the PHP script is complete.

Now, uncomment the line commented out in PHP. ini in the "Settings" section and restart Apache. Now the debugger is installed, and eclipse can be attached to it.

Now, design the debugging environment in eclipse. Create a new test4.php file. Leave it empty first. ClickRun> debug. In the left-side pane, select PHP dbg script and clickNew. Now goFileTab, enter the current projectDebugarticleAnd files to be debuggedTest4.php. Now goEnvironmentTab, and thenInterpreterSub-tab. Find the php.exe file in the PHP installation directory (my files are c: \ apps \ php5.0.3 \ php.exe ). ClickRemote debugSub-tab, selectRemote debugIf windows is not used, cancel the "open with dbgsession URL in internal browser box" check box. Set the remote Source Path to the absolute path (not the web path) of the PHP script to be tested (my setting is c: \ www \ debugarticle \ test4.php ). ClickDebug.

Now the debug perspective should be loaded, as shown in figure 8. Otherwise, clickWindow> open perspective> OtherAnd selectDebug.

Figure 8. debug perspective in eclipse

Now you can set the breakpoint.

For the plug-ins and extended versions used in this article, the breakpoint function is required because PHP will buffer the output before sending it to the browser. In addition, you need not only to set a breakpoint to refresh the currently displayed data to the web browser, so define test4.php as shown in the following figure and figure 8.

Listing 4. Setting and creating breakpoints

<? Phpfunction 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! ");?

Breakpoint ()The function refreshes the buffered output and other buffered data to the Web browser. PairSleep (. 1)So that the code is abortedDebugbreak ()Previously, the server had enough time to refresh the data to the web browser. This function is an internal function extended by the PHP debugger downloaded earlier. In this way, callBreakpoint ()The HTML block,Print ()AndEcho ()The statement data is refreshed to the browser, and the code execution is aborted.

After writing the code like in Listing 4, you can open the browser and point to test4.php, or you can view the PHP browser window (My http: // localhost/debugarticle/test4.php ). Each time a file is input and saved, the debugging sequence is started in the PHP browser window. If you are not using Windows, check test4.php in your browser. After saving the file, useF8Or clickRun> resumeContinue code execution. Continue to do this until the output in the last row isEnd!(See Figure 9, 10, and 11 ).

Figure 9. Initial PHP browser output to the first breakpoint

Note how to display the execution as suspended in the debug window in Figure 9.

Figure 10. php browser output after the first breakpoint and before the second breakpoint

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

Figure 11. Complete PHP browser output

Note: the code in the debug window in 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 have seen the advantages of developing with phpeclipse and debugger extensions, it is hard to imagine what will happen without it.

Conclusion

Now you have added Application of error reports, print statements, phpeclipse, and debugger extensions to PhP debugging technology. You can reduce the number of errors in each line of code, become more effective PHP coding personnel. See references for some PHP tutorials to test these new skills.

Download sample code for PHP debugging

References

Learning

    • For more information, see the original article on the developerworks global site.

    • Learn how to install Java on Windows and UNIX-based systems.
    • Visit eclipse.org to obtain comprehensive information about programming and how to use it.
    • "Getting started with the eclipse platform" (developerworks, November 2002) 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 and an interactive tool that helps debug PHP scripts. Please read this tutorial on installing and locking ing the debugger.
    • To learn more about eclipse, visit the Eclipse project resources on developerworks.
    • To learn more about PhP, visit the PHP project resources on developerworks.
    • For more information about Error Reporting, see the PHP manual.
    • Read the instructions for installing PHP and apache2 on Linux.
    • Read the instructions for installing PHP and apache2 on Windows.
    • For a series of developerworks tutorials on PHP programming, see "Learning PHP, Part 1", learning PHP, Part 2 and learning PHP, part 2.
    • Keep an eye on developerworks technical events and webcasts.
    • Visit the open source code area on developerworks for a wide range of how-to information, tools, and project updates to help develop and use them for IBM products.

Obtain products and technologies

    • Download the latest PHP version from php.net.

    • Download the latest version of Apache 2.
    • Download Java from sun.
    • Download the latest version of eclipse from eclipse.org.
    • Download phpeclipse from SourceForge. Decompress eclipse to eclipse-install-Dir, and then decompress phpeclipse to eclipse-install-Dir. When installing the extension, follow phpeclipse instructions. However, comment out the lines that require the PHP extension to be installed and configured in the PHP. ini file. Uncomment these lines when preparing to use the debugger.
    • Order free SEK for Linux. This set of DVDs (two) includes the latest IBM trial software for Linux from DB2, Lotus, rational, Tivoli and websphere.
    • Use the IBM trial software to transform your next open source code development project, which can be downloaded or obtained through a DVD.

Discussion

    • Join developerworks by participating in developerworks blogsCommunity.

About the author

Taylor Anderson graduated from briham young University in 2004 and obtained a computer science degree. Now 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 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.