Dynamic Web PHP Programmer's Optimized debugging techniques and techniques

Source: Internet
Author: User
Tags execution flush flushes variables parse error php file php and sleep


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, it also downloads it.



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:





				

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:





				

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:





				

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:







				

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





				






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.




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 was in Linux? When developing an application, there is no convenient GUI to tell me where the bug is, and I quickly find that the more print statements I put in the program, the greater the chance I have of reducing the scope of bugs to one line in my application. Please create another PHP file test2.php and define it as shown in Listing 2.

Listing 2: Showing all the variables submitted through get





				

<?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.





Now click the Send Get Request button, and note that only the keys for the $_get request appear on the browser, and the correct values do not appear. You can place a print statement in a loop to verify that data does exist in each element in the Foreach loop. See Listing 3.






Listing 3: Verifying the functionality of the code with the print statement





				

... 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.




Now that the application has correctly received the variable from the GET request, it must be a bug in the code. After viewing, note that the variable used to display the value $j is incorrect. The $i is specified in the foreach statement, so it must have the correct value, but unintentionally enter the $j. So by replacing the $j with a $i, you quickly fix the error, reload the page, and see the correct output, as shown in Figure 4.




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).




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.




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).




The following is a breakpoint set in PHP with 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 a 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 you want to debug test4.php . Now go to the Environment tab, and then to the interpreter Sub-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 browser box check box. 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 . The

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




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);





The breakpoint () function flushes buffered output and other buffered data to a Web browser. Calls to sleep (. 1) are required so that the server has enough time to flush the data to the Web browser before DebugBreak (), which is the intrinsic function of the PHP debugger extension that was previously downloaded. This way, calling breakpoint () flushes the data from the HTML block, print (), and Echo () statements to the browser, and then aborts the execution of the code.

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 end! So far (see figures 9, 10, and 11).




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




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




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.




Related Article

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.