Getting start Debugging and Profiling PHP with Xdebug

View: 731    Dowload: 0   Comment: 0   Post by: hanhga   Category: Php&mySql   Fields: Other

PHP is the most popular language for web development, but a common criticism against it used to be that it lacked a suitable debugger. Developers using languages like Java and C# enjoy a powerful suite of debugging tools, often integrated directly with their IDEs. But the disconnected nature of web servers and PHP IDEs prevented us from having many of the same tools available. We manually added debug statements in our code… until Xdebug filled the void.

Xdebug is a free and open source project by Derick Rethans and is probably one of the most useful PHP extensions. It provides more than just basic debugging support, but also stack traces, profiling, code coverage, and so on. In this article you’ll see how to install and configure Xdebug, how to debug your PHP application from Netbeans, and how to read a profiling report in KCachegrind.

Installing and Configure Xdebug

If you are using XAMPP or MAMP, Xdebug comes preinstalled; you just need to enable it in your php.ini. If you are using a package based installation on a platform such as Ubuntu, you can install it through your package manager with a command like apt-get install php5-xdebug.

The entries for Xdebug in my php.ini look like this:


zend_extension specifies the path to the Xdebug module. The xdebug.remote_enable value toggles whether the extension is active or not. xdebug.remote_host is the name or the IP address of your system (here I’ve specified localhost because I’m working all on the same machine, but the value can be an IP Address or a DNS hostname if you need to specify something different for your setup).xdebug.remote_port is the port on which the client listens for a connection from Xdebug (9000 is the default value).

When you use Xdebug, it’s important to make sure you are not using any other Zend extensions since they may conflict with Xdebug.

There are other installation options as well. The Xdebug website provides a simple wizard to guide you through installation. You can take the output of phpinfo() or php –i and paste it in the text box and have the wizard analyze your server’s configuration and instruct you on how to compile Xdebug for your machine.


More often than not it’s tempting to use the var_dump() and exit/die() combination for debugging. But the problem with this approach is that you have to modify the code for debugging; you must remember every place you added output statements and remove them after debugging is finished. Xdebug overcomes this by letting you pause your application’s execution where ever you want. Then you can inspect the variables’ values in that scope to get better insight into what PHP is doing.

You can easily configure Netbeans to act as an Xdebug client. Open the options window (Tools > Options) and go to the debugging tab for the PHP section. Enter the debugging port given in php.ini and a Session ID which you’ll need to pass with the requests you want to debug. Now you’ll be able to run the debugger by clicking Debug in the tools tab.

With your source file open, press the Debug button in the toolbar to start debugging. It will open up the application in a browser, and PHP’s execution will pause at the first line of the file if you have enabled the “Stop at first line” option in the Options window. Otherwise, it will run until it encounters the first breakpoint. From there you can continue to the next break point using the continue button.

Notice in the brower’s URL bar the XDEBUG_SESSION_START parameter. To trigger the debugger you must pass XDEBUG_SESSION_START as a request parameter (GET/POST) or XDEBUG_SESSION as a cookie parameter.

There are some other useful actions in the debugging toolbar. They are:

Step over – Step over the currently executing line

Step into – Step into the function (for non-built-in functions)

Step out – Step out of the current function

You can add breakpoints by clicking the line number in the editor’s margin and then pause execution on them. They can be removed by clicking on them again. Alternatively, go to Window > Debugging > Breakpoints which will list all breakpoints in your program and you can select/deselect only those you needed.

While running, the state of the variables in the current scope are shown in the variables window. It will show the values of local variables and super global variables like $_COOKIE$_GET$_POST and$_SERVER. You can watch their values change as you step through through the statements.


Profiling is the first step when optimizing any application. Profiling tools record important details like the time it takes for statements and functions to execute, the number of times they are called, and so on. The output can be analyzed to understand where the bottlenecks are.

Xdebug can also be used as a profiling tool for PHP. To start profiling your applications, add the following settings to php.ini:

xdebug.profiler_enable = 1
xdebug.profiler_output_name = xdebug.out.%t
xdebug.profiler_output_dir = /tmp
xdebug.profiler_enable_trigger = 1

Profiling is disabled by default in Xdebug, so xdebug.profiler_enable is used to enable it.xdebug.profiler_output_name is the filename of the profiler log (the %t specifier appends a timestamp to the filename; see the documentation for a full list of specifiers). Xdebug stores the profiling output in the directory specified by xdebug.profiler_output_dir. You can can change this to a location of your choice, but remember it must have write permissions for the user account under which the PHP script is run.

Profiling degrades performance since the PHP engine need to look af each function call and log its details, so you don’t want to run it all the time. xdebug.profiler_enable_trigger instructs Xdebug to perform profiling only when XDEBUG_PROFILE is passed as a GET or POST parameter.

The log file created by Xdebug can be small or large depending on what the application is doing. Also, it’s not really reader friendly. You’ll want to use programs like KCachegrind or Webgrind to view them. KCachegrind is a profile data visualization tool for KDE, which needs a Unix environment to run, whereas Webgrind is a web-based tool.

Opening the profiling long file in KCachegrind will show the cost of each function call starting at main(). Here is the KCachegrind visualization of profiling output of a function to find a factorial:

The left side panel (Function Profile) shows the time taken by each function in their execution order. The top right panel graphically displays the same information with the size corresponding to the cost of the function. The call graph represents the relationship between functions in the application. In this example there are only two functions, main() and fact()fact() is a recursive function, which is indicated using a cycle in the graph.

While optimizing your code, you should look for the areas with highest total cost. More often than not, I/O operations will have the highest cost. Remember to reduce them as much as possible. Lazy load files wherever that makes sense.

Suppose you have a class named Orders which will give you a list of all orders and their details from your web store.

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'] = 
            $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;

This class has two methods: getAll() and getDetails(). When you call the getAll() method, it will get all of the records from the orders table and loop through them to get the details of all records.

Let’s have a look at the profiling information.

Though the absolute figures are not significant since they depend on the platform and runtime conditions, you will get an idea about relative cost of different functions. Notice that some functions are called hundreds of times (which is bad of course). The code doesn’t need to loop through all of the orders and get the details of each order individually. Let’s rewrite the getAll() function to use a JOIN instead.

pubilc function getAll() {
    $orders = array();
    $query = "SELECT * FROM orders o
        JOIN orderdetails d ON o.orderId = od.Id
        ORDER BY o.orderId
    $result = $this->db->query($query);
    while($row =$result->fetch(PDO::FETCH_ASSOC)){
        $orders[] = $row;
    return $orders;

Now the profiling yields a better result since the number of queries has decreased. Also, the code isn’t calling the getDetails() function any more.


Xdebug act as a middleman that controls the execution of PHP programs in the server. In this article you’ve seen two of the most impressive features of Xdebug – debugging support and profiling support.

Its remote debugging allows you to inspect values at runtime, without modifying your program, to get a better understanding of what PHP is doing. Profiling helps uncover bottlenecks in your code so you can optimize it for better performance.

I hope this article helps you realize the benefits of Xdebug and encourages you to start using it right away if you aren’t already. And if you find this a valuable tool, you might even want to consider supporting this great project by buying a support agreement.

Getting start Debugging and Profiling PHP with Xdebug

PHP is the most popular language for web development, but a common criticism against it used to be that it lacked a suitable debugger. Developers using languages like Java and C# enjoy a powerful suite of debugging tools, often integrated directly with their IDEs

Posted on 12-04-2016 


To comment you must be logged in members.

Files with category

  • Twitter-like Hashtag Function in PHP

    Twitter-like Hashtag Function in PHP

    View: 137    Download: 1   Comment: 0

    Category: Php&mySql     Fields: none

    If you ever want a function to hashtag and style words within a string which has '#' next to it like twitter. This piece of code will help

  • PSITS Automated Voting System

    PSITS Automated Voting System

    View: 164    Download: 11   Comment: 0

    Category: Php&mySql     Fields: none

    A free sourcecode for PSITS Automated Voting System develop in PHP programming language. The purposed of the system is to automate the process of voting and maintain the quality of data

  • PHP-University Application System

    PHP-University Application System

    View: 149    Download: 13   Comment: 0

    Category: Php&mySql     Fields: none

    Greeting from Malawi the warm heart of Africa. I developed this university registration system project just to share with the people who can make use of the project like this and at the same time for others like students who can learn from it. This...

  • School Event Management System in PHP/MSQLi

    School Event Management System in PHP/MSQLi

    View: 134    Download: 0   Comment: 2

    Category: Php&mySql     Fields: none

    This School Event Management System can create school events such as Volleyball games, Basketball, Cultural presentation, Election of school officers etc . During school election Instead of having a compile list of candidates and voters this system...

  • Resort Reservation System with PayPal/Credit Card/Debit Card Payment

    Resort Reservation System with PayPal/Credit Card/Debit Card Payment

    View: 127    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    This reservation system has the ability to help its customers find available rooms, cottages and even function hall for their convenience . And in here, they will also have the idea of the room rates where they can quickly reserve for their family...

  • Activity log

    Activity log

    View: 132    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    Simple program to track user's activity log-in time and online/offline status.

  • Electricks - eCommerce

    Electricks - eCommerce

    View: 128    Download: 0   Comment: 0

    Category: Php&mySql     Fields: none

    Electricks is an e-commerce website built using PHP, Bootstrap and some jQuery plugins. It has all the major functionalities of a typical e-shop. This project was used to present in Southern Luzon State University - Lucban. Feel free to use this code...

  • Simple Email App Using PHP

    Simple Email App Using PHP

    View: 108    Download: 1   Comment: 0

    Category: Php&mySql     Fields: none

    Creating a simple PHP script using mail function for sending out emails.

File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd