2 min read

PHP Debugging (Xdebug)

Xdebug is an extension for PHP to assist with debugging and development. It upgrades PHP's native var_dump() function, adds stack traces for Notices, Warnings, Errors and Exceptions, and most importantly, enables Step Debugging.


1. Installation

Xdebug is a PHP extension that needs to be installed and enabled in your php.ini file.

# Linux (Ubuntu/Debian)
sudo apt-get install php-xdebug

2. Configuration (php.ini)

To enable step debugging, you typically add the following to your php.ini or xdebug.ini:

[xdebug]
zend_extension=xdebug
xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.client_host=127.0.0.1
xdebug.client_port=9003

3. Step Debugging

Step debugging allows you to interactively walk through your code to see what is happening.

  1. Set a Breakpoint: In your IDE (like VS Code or PhpStorm), click next to a line number to set a red dot.
  2. Listen for Connections: Turn on the "Start Listening for PHP Debug Connections" button in your IDE.
  3. Run Script: Refresh your browser. The execution will pause at your breakpoint.

4. Better var_dump()

Without Xdebug, var_dump() output is plain text and hard to read for complex arrays. Xdebug formats it with HTML, colors, and collapsible limits.

$arr = ['a' => 1, 'b' => [1, 2, 3]];
var_dump($arr);
// With Xdebug, this renders as a structured, colorful HTML table.

5. Profiling

Xdebug can also profile your PHP scripts to find bottlenecks.

  • Set xdebug.mode=profile.
  • It generates cachegrind files that can be viewed in tools like KCacheGrind or QCacheGrind.

programming/php/php programming/php/php-error-handling