Home > Backend Development > PHP Tutorial > PHP Master | Debugging and Profiling PHP with Xdebug

PHP Master | Debugging and Profiling PHP with Xdebug

William Shakespeare
Release: 2025-02-25 23:30:11
Original
776 people have browsed it

Xdebug: Powerful debugging and performance analysis tool for PHP developers

Core points:

  • Xdebug is a powerful, free and open source PHP extension that provides debugging support, stack trace, performance analysis, code coverage and other functions. It allows developers to pause the execution of the application at any time and check the value of variables to better understand how PHP is running.
  • Xdebug can be used as a performance analysis tool for PHP applications, recording important details such as statements and functions execution time and number of calls. Analyzing these outputs allows you to understand where the bottleneck lies, thereby optimizing your application for performance.
  • To use Xdebug, it needs to be installed and configured correctly. Xdebug is preinstalled in XAMPP or MAMP, just enable it in php.ini. For other platforms, it can be installed through the package manager. It should be noted that using other Zend extensions may conflict with Xdebug.

PHP is the most popular language in web development, but it has often been criticized for its lack of a suitable debugger. Developers using languages ​​like Java and C# can use powerful suites of debugging tools, often directly integrated into their IDEs. But the separation of web servers and PHP IDEs has prevented us from using many of the same tools. We manually add debug statements to the code... until Xdebug fills this gap. Xdebug is a free open source project created by Derick Rethans and is probably one of the most useful PHP extensions. It provides not only basic debugging support, but also stack trace, performance analysis, code coverage, and more. This article will explain how to install and configure Xdebug, how to debug PHP applications from Netbeans, and how to read performance analysis reports in KCachegrind.

Installing and configuring Xdebug

If you are using XAMPP or MAMP, Xdebug is pre-installed; you just need to enable it in php.ini. If you use package-based installation on platforms like Ubuntu, you can install it through the package manager using a command like apt-get install php5-xdebug. The entry for Xdebug in my php.ini looks like this:

<code>[xdebug]
zend_extension="/Applications/MAMP/bin/php5.2/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000</code>
Copy after login
Copy after login

zend_extensionSpecify the path to the Xdebug module. xdebug.remote_enableWhether the value toggle extension is active. xdebug.remote_host is your system name or IP address (here I specified localhost because I both work on the same machine, but if you need to specify a different value for your settings, the value can be an IP address or DNS hostname). xdebug.remote_port is the port where the client listens for from the Xdebug connection (9000 is the default). When using Xdebug, be sure to make sure you are not using any other Zend extensions as they may conflict with Xdebug. There are other installation options. The Xdebug website provides a simple wizard to guide you through the installation process. You can get the output of phpinfo() or php –i, paste it into a text box, let the wizard analyze your server configuration, and guide you on how to compile Xdebug on your machine.

Debug

Usually, it is tempting to debug using a combination of var_dump() and exit/die(). But the problem with this approach is that you have to modify the code to debug; you have to remember to add each location of the output statement and delete it after debugging is done. Xdebug overcomes this by allowing you to pause the execution of your application wherever you need it. You can then check the values ​​of variables in that scope to better understand how PHP is running. You can easily configure Netbeans to act as an Xdebug client. Open the Options window (Tools > Options), and go to the Debug tab in the PHP section. Enter the debug port and session ID given in php.ini, and you need to pass the session ID using the request you want to debug. You can now run the debugger by clicking Debug in the Tools tab.

PHP Master | Debugging and Profiling PHP with Xdebug

After opening the source file, click the "Debug" button in the toolbar to start debugging. It will open the application in the browser and if the "Stop on first line" option has been enabled in the Options window, the execution of PHP will be paused on the first line of the file. Otherwise, it will run until the first breakpoint is encountered. From there, you can use the Continue button to continue to the next breakpoint. Please note that the XDEBUG_SESSION_START parameter in the browser URL bar. To trigger the debugger, XDEBUG_SESSION_START must be passed as the request parameter (GET/POST) or XDEBUG_SESSION as the cookie parameter. There are some other useful operations in the debug toolbar. They are:

  • Step by step – Skip the currently executing line
  • Single-step into function (for non-built-in functions)
  • Single-step out – jump out of the current function

You can add a breakpoint by clicking the line number in the editor margin and then pause execution at the breakpoint. They can be deleted by clicking them again. Or, go to the window > Debug > Breakpoints, which will list all breakpoints in the program, you can select/deselect only breakpoints you need. At runtime, the status of the variable in the current scope is displayed in the variable window. It will display the values ​​of local variables and super global variables such as $_COOKIE, $_GET, $_POST, $_SERVER, and

). You can observe how their values ​​change as you step through the statement.

PHP Master | Debugging and Profiling PHP with Xdebug

Performance Analysis

Performance analysis is the first step in optimizing any application. Performance analysis tools record important details, such as the time required for statements and functions to execute, the number of calls, etc. The output can be analyzed to understand where the bottleneck lies. Xdebug can also be used as a performance analysis tool for PHP. To start analyzing your application, add the following settings to php.ini:
<code>[xdebug]
zend_extension="/Applications/MAMP/bin/php5.2/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000</code>
Copy after login
Copy after login

Property analysis is disabled by default in Xdebug, so xdebug.profiler_enable is used to enable it. xdebug.profiler_output_name is the file name of the performance analyzer log (the %t specifier appends the timestamp to the file name; see the documentation for a complete list of specifiers). Xdebug stores the performance analysis output in the directory specified by xdebug.profiler_output_dir. You can change it to anywhere you choose, but remember that the user account running the PHP script must have write permissions to it. Performance analysis can degrade performance because the PHP engine needs to view each function call and record its details, so you don't want to run it all the time. xdebug.profiler_enable_trigger Instructs Xdebug to perform performance analysis only when XDEBUG_PROFILE is passed as a GET or POST parameter. The size of the log files created by Xdebug may vary depending on the operation of the application. Also, it's not really easy to read. You need to use programs like KCachegrind or Webgrind to view them. KCachegrind is KDE's performance analysis data visualization tool that requires a Unix environment to run, and Webgrind is a web-based tool. Opening the performance analysis log file in KCachegrind will show the cost of each function call starting from main(). The following is a KCachegrind visualization of the performance analysis output of the factorial function:

PHP Master | Debugging and Profiling PHP with Xdebug

The left panel (function summary) displays the time spent on each function in order of execution. The panel in the upper right corner displays the same information graphically, with the size corresponding to the cost of the function. Call graphs represent the relationship between functions in the application. In this example, there are only two functions, main() and fact(). fact() is a recursive function, represented by a loop in the figure. When optimizing your code, you should look for the area with the highest total cost. Normally, I/O operation is the most expensive. Remember to minimize them as much as possible. Lazy loading of files anywhere meaningful. Suppose you have a class called Orders which will give you a list of all orders and their details from your online store.

<code>xdebug.profiler_enable = 1
xdebug.profiler_output_name = xdebug.out.%t
xdebug.profiler_output_dir = /tmp
xdebug.profiler_enable_trigger = 1</code>
Copy after login

This class has two methods: getAll() and getDetails(). When you call the getAll() method, it will get all records in the orders table and loop through them to get the details of all records. Let's take a look at the performance analysis information.

PHP Master | Debugging and Profiling PHP with Xdebug

Although absolute numbers don't matter, as they depend on the platform and runtime conditions, you will understand the relative costs of different functions. Note that some functions are called hundreds of times (which is of course bad). The code does not need to loop through all orders and get the details of each order separately. Let's override the getAll() function to use JOIN.

<?php
class Orders
{
    protected $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    public function getAll() {
        $orders = array();
        $query = "SELECT * FROM orders";
        $result = $this->db->query($query);
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $row['details'] =
                $this->getDetails($row['orderId']);
            $orders[] = $row;
        }

        return $orders;
    }

    public function getDetails($orderId){
        $details = array();
        $result = $this->db->query("SELECT * FROM orderdetails WHERE orderId = " . $orderId);
        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
            $details[] = $row;
        }
        return $details;
    }
}
Copy after login

Performance analysis now produces better results because the number of queries is reduced. In addition, the code no longer calls the getDetails() function.

PHP Master | Debugging and Profiling PHP with Xdebug

Summary

Xdebug acts as an intermediary and controls the execution of PHP programs in the server. In this article, you've seen two of the most impressive features of Xdebug - debug support and performance analysis support. Its remote debugging allows you to check values ​​at runtime without modifying the program, thus giving you a better understanding of how PHP is running. Performance analysis helps identify bottlenecks in your code so you can optimize them for performance. I hope this article helps you understand the benefits of Xdebug and encourages you to start using it right away (if you haven't used it yet). If you find this a valuable tool, you may even want to consider supporting this great project by purchasing a support agreement.

(Please note: the above picture placeholder needs to be replaced with the actual screenshot.)

The above is the detailed content of PHP Master | Debugging and Profiling PHP with Xdebug. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template