search
HomeBackend DevelopmentPHP TutorialOptimization and debugging techniques and techniques for PHP programmers_PHP tutorial

Optimization and debugging techniques and techniques for PHP programmers_PHP tutorial

Jul 13, 2016 pm 05:34 PM
aphpintroduceoptimizationBagandappSkilltechnologymethodofprogrammerdebug

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.

Settings

To learn the concepts described in this article, you will need PHP, a web server, and Eclipse. 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 introduced in this article, you need to install Eclipse V3.1.1 and the plug-in PHPEclipse V1.1.8. Since Eclipse requires Java® technology, you'll also need to download it.

You also need 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.

​See Resources for download information. Now about the error messages.

Error message

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 be used to your advantage, as they will 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.

PHP error report

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:

            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:

            display_errors = On
            

The default value of the 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:

            error_reporting = E_ALL & ~E_NOTICE
            

  重新启动 Apache,就全部设置好了。接下来,将学习如何在 Apache 上做同样的事。

  服务器上的错误报告

  依赖于 Apache 正在做的工作,在 PHP 中打开错误报告可能没法工作,因为在计算机上可能有多个 PHP 版本。有时很难区分 Apache 正在使用哪个 PHP 版本,因为 Apache 只能查看一个 php.ini 文件。不知道 Apache 正在使用哪个 php.ini 文件配置自己是一个安全问题。但是,有一种方法可以在 Apache 中配置 PHP 变量,从而保证设置了正确的出错级别。

  而且,最好知道如何在服务器端设置这些配置变量,以否决或抢占 php.ini 文件,从而提供更高级别的安全性。

  在配置 Apache 时,应该已经接触过 /conf/httpd.conf 中 http.conf 文件中的基本配置。

  要做在 php.ini 文件中已经做过的事,请把下列各行添加到 httpd.conf,覆盖任何 php.ini 文件:

            php_flag  display_errors        on
            php_value error_reporting       2039
            

  这会覆盖在 php.ini 文件中为 display_errors 已经设置的标志,以及 error_reporting 的值。值 2039 代表 E_ALL & ~E_NOTICE。如果愿意采用 E_ALL,请把值设为 2047。同样,还是要重启 Apache。

  接下来,要在服务器上测试错误报告。
 测试错误报告

  如果启动了错误报告,会节约许多时间。PHP 中的错误会指向代码中的错误。请创建一个简单的 PHP 文件 test.php,并像清单 1 所示一样定义它。

清单 1. 一个Optimization and debugging techniques and techniques for PHP programmers_PHP tutorial的简单 PHP
            <?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 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
Optimization and debugging techniques and techniques for PHP programmers_PHP tutorial

Error reporting is now enabled! Next, use print statements to help debug your application.

Introduction to the print statement

Because functional bugs in an application do not generate errors, knowledge of how to properly place and use print or die statements to debug PHP applications is a great asset in any debugging strategy. 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 through 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 statement for debugging

In my days as a programmer, when I was developing applications on Linux® and there was no convenient GUI that could tell me where the bugs were, I quickly found that the more print statements I put in my program, the more I lost in my application. The greater the chance of narrowing the scope of the bug to one line. Create another PHP file, test2.php, and define it as shown in Listing 2.

Listing 2. Displaying all variables submitted via GET
            <?php $j = "";
            print("Lets retrieve all the variables submitted to this ");
            print("script v </p>
<p align="left"></p><div style="display:none;">
<span id="url" itemprop="url">http://www.bkjia.com/PHPjc/508474.html</span><span id="indexUrl" itemprop="indexUrl">www.bkjia.com</span><span id="isOriginal" itemprop="isOriginal">true</span><span id="isBasedOnUrl" itemprop="isBasedOnUrl">http: //www.bkjia.com/PHPjc/508474.html</span><span id="genre" itemprop="genre">TechArticle</span><span id="description" itemprop="description">This article describes various methods of debugging PHP applications, including opening error reports in Apache and PHP, and by A simple PHP script to place strategic print statements, find...</span>
</div>
<div class="art_confoot"></div>
Statement
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
Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Explain Fibers in PHP 8.1 for concurrency.Explain Fibers in PHP 8.1 for concurrency.Apr 12, 2025 am 12:05 AM

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP Community: Resources, Support, and DevelopmentThe PHP Community: Resources, Support, and DevelopmentApr 12, 2025 am 12:04 AM

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function