Summary of debugging techniques for PHP programmers_PHP tutorial

WBOY
Release: 2016-07-21 15:43:01
Original
941 people have browsed it

This article covers various ways to debug PHP applications, including turning on error reporting in Apache and PHP, as well as finding the source of more difficult bugs by strategically placing print statements in a simple PHP script. You'll also learn about the PHPEclipse plug-in for Eclipse, a flexible development environment with real-time syntax parsing capabilities, and the DBG debugger extension for PHPEclipse.
Introduction
There are many PHP debugging techniques that can save a lot of time when coding. An effective yet basic debugging technique is to turn on error reporting. Another, slightly more advanced technique involves using print statements, which can help pinpoint harder-to-find bugs by displaying what actually appears on the screen. PHPEclipse is an Eclipse plug-in that highlights common syntax errors and can be used in conjunction with the debugger to set breakpoints.

Setup
To learn the concepts described in this article, PHP, a web server, and Eclipse are required. The debugger extension supports PHP version V5.0.3.
We need a web server to parse pages created with PHP and display them to the browser. Apache2 is used in this article. However, any web server will suffice.
To take advantage of some of the debugging techniques described in this article, you need to install Eclipse V3.1.1 and the plug-in PHPEclipse V1.1.8. Since Eclipse requires Java™ technology, download it as well.
Also requires the PHP debugger extension module. Installing it is a little tricky. Please follow the instructions for installing the debugger extension carefully. Now, comment out the lines in the php.ini file that require the PHP extension to be loaded and configured. Uncomment it when you need to use the debugger.
Please see Resources for download information. Now about the error messages.

Error messages
Error messages are your first line of defense as a developer. No one wants to develop code in PHP on a server that is not configured to display error messages. However, please remember that when you have debugged your code and are ready to run it, you should make sure that error reporting is turned off as you do not want your site visitors to see error messages as this will give them enough information to exploit the site's weaknesses and Hack the site.
Error messages can also serve themselves well, as they show the correct line of code that threw or generated the error. This way, debugging becomes a matter of looking in the browser at the line number where the generated error appears, and inspecting that line in the code. Later, you'll see that the PHPEclipse plug-in can be of great assistance during development and debugging by underlining syntax errors on the fly and marking syntax errors with a red "x" when saving the file.
Let’s first look at how to enable error reporting and set the level of error reporting in the php.ini file. You'll then learn how to override these settings in Apache's configuration files.
Error reporting for PHP
There are many configuration settings in the php.ini file. You should have set up your php.ini file and placed it in the appropriate directory, as documented in the instructions for installing PHP and Apache 2 on Linux (see Resources). There are two configuration variables that you should be aware of when debugging PHP applications. Here are the two variables and their default values:

Copy the code The code is as follows:

display_errors = Off
error_reporting = E_ALL

The current default values ​​of these two variables can be found by searching for them in the php.ini file. The purpose of the display_errors variable is obvious - it tells PHP whether to display errors. The default value is Off. However, to make the development process easier, set this value to On:
Copy the code The code is as follows:

display_errors = On

The default value of error_reporting variable is E_ALL. This setting will show everything from bad coding practices to harmless tips to errors. E_ALL is a bit too granular for development purposes, as it also displays hints on the screen for small things (such as variables not being initialized), which messes up the browser's output. I only want to see errors and bad coding practices, but not harmless tips. So, please replace the default value of error_reporting with the following value:
Copy the code The code is 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 on the server
Depending on what Apache is doing, turning on error reporting in PHP may not work since there may be multiple versions of PHP on the computer. Sometimes it's difficult to tell which PHP version Apache is using 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 issue. However, there is a way to configure PHP variables in Apache so that the correct error level is set.
Also, it's a good idea to know how to set these configuration variables on the server side to override or preempt the php.ini file, thus providing a higher level of security.
When configuring Apache, you should have already been exposed to the basic configuration in the http.conf file in /conf/httpd.conf.
To do what you have already done in the php.ini file, add the following lines to httpd.conf, overwriting any php.ini files:
Copy code The code is as follows:

php_flag display_errors on
php_value error_reporting 2039

This will overwrite the flags already set for display_errors in the php.ini file, and the value of error_reporting. The value 2039 represents E_ALL & ~E_NOTICE. If you prefer to use E_ALL, set the value to 2047. Again, you still need to restart Apache.
Next, test error reporting on the server.
Test error reporting
If error reporting is enabled, it will save a lot of time. Errors in PHP point to errors 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 errors
Copy the code The code is as follows:

print("The next line generates an error.
");
printaline("PLEASE?");
print("This will not be displayed due to the above error.");
?>

The first print() statement displays its contents to the web browser. But the second statement generates an error and displays it on the web page. This causes the last print() statement to not work, as shown in Figure 1.
Figure 1. Generation error
生成错误

Bug reporting now enabled! Next, use print statements to help debug your application.
Introducing the print statement
Because functional bugs in the application do not generate errors, knowledge of how to properly place and use print or die statements to debug PHP applications is an important part of all debugging strategies. Very good asset. You can use the print statement to narrow down the location of problem statements in the code. These statements have no syntax errors and are not bugs, but they are bugs in terms of the function 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 the content you want to save in the database is not saved at all.
Suppose you are processing form data sent via a GET request and want to display information to the browser, but for some reason, the data is not submitted correctly, or cannot be read correctly from the GET request. To debug this type of problem, it is important to know what the value of the variable is using a print() or die() statement. The
die() statement halts program execution and displays text on the web browser. The die() statement is particularly useful if you don't want to comment out the code, and you only want to display the information before the error and the error message, but don't want to display the subsequent information.
Let’s test this concept using print statements in PHP
Use print statements for debugging
In my days as a programmer, there was no convenient GUI when I was developing applications on Linux® can tell me where the bug is, and I quickly found that the more print statements I put in my program, the better my chance of narrowing the bug down to a single line in my application. Create another PHP file, test2.php, and define it as shown in Listing 2.

Listing 2. Display all variables submitted via GET

Copy code The code is as follows:

$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
");
}
if($_GET ['Submit'] == "Send GET Request")
$j = "done!
";
?>

Name:

Email:




You might find the bug in Listing 2 very easily! You are great! But please note that this is a very simple script and is just shown as an example of using print statements for debugging. This script simply extracts all variables from the GET request and displays them on the browser if any. A form is also provided to send variables to the server with a GET request for testing. Take a look at the output, shown in Figure 2.
Figure 2. Output of test2.php
test2.php 的输出

Now click on the Send GET Request button, please note that only the <font face="新宋体">$_GET</font> requested key is displayed on the browser and none of the correct values ​​are displayed. You can put a print statement inside the loop to verify that the data actually exists in each element in the <font face="新宋体">foreach</font> loop. See Listing 3.
Listing 3. Use print statement to verify the function of the code

Copy the code The code is as follows:

...
foreach($_GET as $key => $i){
print("Correct data? " . $_GET[$key] . "
");
print("$key= $j
");
}
...

放进去的 print 语句是粗体。注意,现在已经知道在 Web 浏览器上显示的 $key 值是正确的,但是由于某些原因,值没有正确地显示。请看新的输出,如图 3 所示。
图 3. 修改后的 test2.php 的输出
修改后的 test2.php 的输出

现在已经知道应用程序正确地从 <font face="新宋体">GET</font> 请求接收到了变量,那么肯定是在代码中有 bug。查看之后注意到,用来显示值的变量 <font face="新宋体">$j</font> 是错误的。在 <font face="新宋体">foreach</font> 语句中指定的是 <font face="新宋体">$i</font>,所以它肯定会有正确的值,但是无意之中输入了 <font face="新宋体">$j</font>。所以通过把 <font face="新宋体">$j</font> 替换成 <font face="新宋体">$i</font>,迅速地修正了错误,重新载入页面之后,就看到了正确的输出,如图 4 所示。


图 4. 修正后的 test2.php 的输出
修正后的 test2.php 的输出

现在可以删除或注释掉刚才添加的 print 语句了,因为已经发现了代码中的 bug。注意,这只是在调试应用程序时可能遇到的许多错误中的一个很小的子集。对于使用数据库时可能遇到的问题,一个好的解决方案是输出 SQL 语句,以确保执行的 SQL 就是想要执行的。

现在要来看看如何使用 Eclipse IDE 和 PHPEclipse 插件及调试器扩展进一步在调试历程中提供帮助。

使用 PHPEclipse

您可能用过 Eclipse,但是可能不熟悉它。请参阅 参考资料 获得 Eclipse 平台的介绍。

用于 Eclipse 的 PHPEclipse 插件是用来开发 PHP 应用程序的一个流行工具。请启动 Eclipse 并把工作区目录指定为 Apache 的 www 目录(在我的机器上是 c:\www)。现在单击 File > New > Project。会弹出 New Project 向导。双击 PHP 文件夹并选择 PHP Project。单击 Next,输入项目名称 debugArticle,并单击 Finish

如果把 Web 服务器设置为在端口 80 上侦听,那么不需要做任何修改。否则,请转到 Navigator 窗口,在 PHP 项目 debugArticle 上右击,选择 Properties,然后单击 PHP Project Settings。单击 Configure Workspace Settings 然后修改合适的 localhost 或者添加 Web 服务器侦听的端口(例如 http://localhost:8080)。单击 Apply 完成设置。

Navigator 窗口应当显示项目和一个 .project 文件。在项目上右击,就像前面做的那样,只是这次选择 New > PHP File。用想要创建的 PHP 文件的名称 test3.php 替换 *.php,然后单击 Finish。在 Eclipse IDE 中应当出现一个新文件。可能需要导航到窗口底部的 PHP 浏览器来查看 PHP 文件的当前输出(参见图 5)。


图 5. Eclipse 的 PHPEclipse 插件
Eclipse 的 PHPEclipse 插件

注意,只有 Windows® 的用户可以像清单 5 所示的那样使用 PHP 浏览器。通过打开独立浏览器窗口并把浏览器指向测试脚本所在目录,也可以使用同样的功能。

现在来演示这个应用程序,证明它的强大能力。

在 “使用调试器” 一节中,将学习如何用 Eclipse、PHPEclipse 和前面下载的调试器 PHP 扩展来调试 PHP 应用程序。先从学习如何使用它的语法解析功能开始。

语法解析和加下划线

先从查看 PHPEclipse 如何提供帮助调试 PHP 应用程序的实时语法解析功能开始。要看这个特性的实际应用,先从在 Eclipse 中定义 test3.php 开始,如下所示。

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

注意,在清单 4 中加下划线的两个字符在 Eclipse 中加了下划线,提示语法不正确。按 Ctrl+S 保存文件,会在 Eclipse 中显示解析错误:在代码中与解析错误对应的行上会加上红 “x”,如图 6 所示。


图 6. 语法错误强调
语法错误强调

现在演示 PHP 浏览器。这个窗口提供了当前 PHP 脚本的预览,如图 6 所示。

从上面定义的 test3.php 中删除逗号(<font face="新宋体">,</font>)。按 Ctrl+S 保存文件,然后观察 PHP 浏览器窗口的更新,显示了 Hello World(参见图 7)。


图 7. 在 PHPEclipse 中预览 PHP 脚本
在 PHPEclipse 中预览 PHP 脚本

下面是用调试器在 PHP 中设置断点。

使用调试器

使用调试器,可以设置断点并查看 PHP 代码到所设断点之前的浏览器输出。然后可以继续代码的执行并查看到下一断点之前的浏览器输出,然后再到下一个,直到 PHP 脚本完成。

现在把 “设置” 一节中在 php.ini 中注释掉的行取消注释,并重新启动 Apache。现在装入了调试器,Eclipse 能够和它挂上了。

现在在 Eclipse 中设计调试环境。请创建新的 test4.php 文件,先保持为空。现在单击 Run > Debug。在左侧面板中选择 PHP DBG Script,并单击 New。现在转到 File 选项卡,输入当前项目 debugArticle 以及想要调试的文件 test4.php。现在转到 Environment 选项卡,然后再到 Interpreter 子选项卡。在 PHP 的安装目录中找到 php.exe 文件(我的是 c:\apps\php5.0.3\php.exe)。现在单击 Remote Debug 子选项卡,选择 Remote Debug,如果没有使用 Windows,请取消 “Open with DBGSession URL in internal browser box” 复选框。把 Remote Source 路径设置成与要测试的 PHP 脚本的绝对路径(不是 Web 路径)相同(我的设置是 c:\www\debugArticle\test4.php)。现在单击 Debug

现在应当装入 Debug 透视图,如图 8 所示。否则,请单击 Window > Open Perspective > Other,并选择 Debug


图 8. Eclipse 中的 Debug 透视图
Eclipse 中的 Debug 透视图

现在可以设置断点了。

对于本文中使用的插件和扩展的版本,断点功能是必需的,因为 PHP 在把输出发送到浏览器之前会缓冲它。除此之外,需要做的不仅仅是设置一个断点把当前显示数据刷新到 Web 浏览器,所以要像下面和图 8 所示那样定义 test4.php。


清单 4. 设置和创建断点

<?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!");
?
Copy after login

<font face="新宋体">breakpoint()</font> 函数会把缓冲的输出和其他缓冲的数据刷新到 Web 浏览器。对 <font face="新宋体">sleep(.1)</font> 的调用是必需的,这样代码中止于 <font face="新宋体">debugBreak()</font> 之前,服务器才有足够的时间把数据刷新到 Web 浏览器,这个函数是前面下载的 PHP 调试器扩展的内部函数。这样,调用 <font face="新宋体">breakpoint()</font> 会把 HTML 块、<font face="新宋体">print()</font><font face="新宋体">echo()</font> 语句的数据刷新到浏览器,然后中止代码执行。

在像清单 4 那样编写完代码之后,可以打开浏览器并指向 test4.php,或者可以查看 PHP 浏览器窗口(我的是 http://localhost/debugArticle/test4.php)。每次输入和保存文件时,在 PHP 浏览器窗口中就已经启动了调试序列。如果不使用 Windows,请通过浏览器查看 test4.php。在保存了文件之后,用 F8 或单击 Run > Resume 继续代码执行。持续这么做,直到最后一行输出是 <font face="新宋体">END!</font> 为止(参见图 9、10 和 11)。


图 9. 初始的到第一个断点的 PHP 浏览器输出
初始的到第一个断点的 PHP 浏览器输出

请注意图 9 中的 Debug 窗口如何把执行显示为挂起的。


图 10. 第一个断点之后到第二个断点之前的 PHP 浏览器输出
第一个断点之后到第二个断点之前的 PHP 浏览器输出

图 10 的 Debug 窗口仍然把执行显示为挂起,而第二组数据显示在 PHP 浏览器中。


图 11. 完整的 PHP 浏览器输出
完整的 PHP 浏览器输出

注意,图 11 的 Debug 窗口中的代码不再挂起,整个脚本已经执行,如图 11 中的 PHP 浏览器所示。

既然已经看到了用 PHPEclipse 和调试器扩展进行开发的优势,那么很难想像没有它会怎么样。

结束语

现在已经向 PHP 的调试技术集中添加了错误报告的运用、print 语句、PHPEclipse 和调试器扩展,您可以通过减少每行代码的错误数量,成为更有效的 PHP 编码人员。请参阅 参考资料 获得一些 PHP 教程,可以在上面测试这些新技能。

下载 Sample code for PHP Debugging

参考资料

学习

  • 您可以参阅本文在 developerWorks 全球站点上的 英文原文

  • 学习如何在基于 Windows 和 UNIX® 的系统上 安装 Java

  • 请访问 Eclipse.org 获得编程和如何使用它的全面信息。

  • Eclipse 平台入门”(developerWorks,2002 年 11 月)提供了 Eclipse 的历史和概述,包括如何安装 Eclipse 和插件的细节。

  • 请访问 PHPEclipse 学习关于安装 PHPEclipse 和如何使用它的更多内容。

  • DBG 是一个全功能的 PHP 调试器引擎,一个交互的工具,有助于调试 PHP 脚本。请阅读 Installing and configuring the debugger 上的这份教程。

  • 要学习关于 Eclipse 的更多内容,请访问 developerWorks 的 Eclipse project resources

  • 要学习关于 PHP 的更多内容,请访问 developerWorks 的 PHP project resources

  • 请参阅 PHP 手册获得更多关于 error reporting 的内容。

  • 请阅读安装 PHP and Apache2 on Linux 的操作说明。

  • 请阅读安装 PHP and Apache2 on Windows 的操作说明。

  • 要获得一系列学习 PHP 编程的 developerWorks 教程,请参阅 “学习 PHP,第 1 部分”、学习 PHP,第 2 部分学习 PHP,第 3 部分

  • 请密切关注 developerWorks technical events and webcasts

  • 请访问 developerWorks 开放源码专区 获得丰富的 how-to 信息、工具和项目更新,有助于用开放源码技术进行开发并把它们用于 IBM 的产品。


获得产品和技术

  • Please download the latest version of PHP from PHP.net.

  • Please download the latest version of Apache 2.

  • Please download Java technology from Sun Microsystems.

  • Please download the latest version of Eclipse from Eclipse.org.

  • Download PHPEclipse from Sourceforge. Extract Eclipse to eclipse-install-dir, and then extract PHPEclipse to eclipse-install-dir. When installing the extension, follow the PHPEclipse instructions. However, comment out those lines where it is required to load and configure the PHP extension in the php.ini file. Uncomment these lines when you are ready to use the debugger.

  • Order the free SEK for Linux, a set of two DVDs 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 as a download or on DVD.


Discuss

  • Join the developerWorks community by participating in developerWorks blogs.



About the author

Tyler Anderson 2004 年从 Brigham Young 大学毕业,获得计算机科学学位。现在是他作为计算机工程硕士生的最后一学期。过去,他作为数据库程序员为 DPMG.com 工作,现在他是位于 Beaverton, Ore 的 Stexar 公司的工程师。



Tyler Anderson graduated from Brigham Young University in 2004 with a degree in Computer Science. He is now in his final semester as a computer engineering master's student. In the past, he worked for DPMG.com as a database programmer, and now he is an engineer at Stexar Corporation in Beaverton, Ore.
Original address http://www.ibm.com/developerworks/cn/opensource/os-debug/

http://www.bkjia.com/PHPjc/320848.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320848.htmlTechArticle
This article describes various methods of debugging PHP applications, including opening error reports in Apache and PHP, and by To place strategic print statements in a simple PHP script, look for...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!