Debugging PHP with Xdebug

Xdebug is an extension for PHP and provides a range of features to improve the PHP development. It provides Step Debugging, Tracing, Profiling, Code Coverage and some error reporting improvements.

For this course however we’ll be focusing on the step debugging part.

Initially when one learns PHP, for debugging, they usually start out with functions like var_dump , print_r and var_export in order to figure out what the value/s of certain variables. This approach works when the variables are limited, but when you’re coding on large projects, dealing with a lot of third party codebase, it becomes time consuming and does not always help as you need to keep moving these statements from one part of code to another, trying to figure out where the values are changing. Also one must remember to remove such statements from code, before committing code to the Git repo. That’s where the Step Debugging part of Xdebug comes in handy.

For a given project, you will have to set it up once but later it saves a lot of time when it comes to debugging or analyzing state of any variable or constant at a given breakpoint.

In order to get started, you need to first install the Xdebug extension, then enable it in php.ini file. After that, you’ll need to have an IDE that is listening for debug sessions on port 9003 (port 9000 for versions of Xdebug prior to 3) by default. Then in browser, you’ll need to install an extesion named Xdebug Helper, that will allow your requests to have necessary headers that allows the PHP process to identify which requests to debug(when using the trigger mode for debugging). Later when PHP requests have necessary headers, it triggers PHP process to create a debugger connection with the IDE on the specified port, and at that point, IDE passes on the breakpoint information to the Xdebug debugger in the PHP process for the request. When the line with breakpoint is reached, the execution is paused until resumed from the IDE(or you can continue execution line by line using Step Debugging)

Depending upon which development tools you are using here are several screencasts showing how to configure Xdebug to debug PHP scripts on WordPress sites:

Video ContentTime
1. PHPStorm with Lando04:38
2. VSCode with Lando05:04
3. VSCode with Local by Flywheel06:22
4. PHPStorm with Local by Flywheel05:24