Using Xdebug with Visual Studio Code is something that’s pretty easy to setup, and is a tremendous help if you’re doing any PHP programming with VS Code. In this post, I’ll go through all the steps to get it all setup and working properly.
For those who haven’t heard of Xdebug before, it is a piece of software that allows you to pause your program while it’s running and see the values that variables that are set, what method is being executed, the call stack, etc…
Configure PHP Linting
Visual Studio Code will perform PHP linting to validate your code when you save your file by default. It is using the PHP executable. As you use VS Code for the first time, you’ll get an error message that the PHP executable cannot be found.
You need to specify the path the PHP executable on your machine. This is done in the settings fil. In this case, we’ll configure the PHP settings for the user.
Open the user settings through the command panel: Press F1, then type ‘user settings’ > Then Press Enter.
This will open two JSON documents. The left document contains the default settings, the right document is your user settings. In the user settings you can override the default settings. To enable PHP linting, you must add three settings.
For the sake of this setup, I’ll assume you’re using MAMP with PHP 7.1.5. If you’re using another version, it shouldn’t be hard to figure what you should change instead.
The first thing you have to do is enable Xdebug. You have to do this from the php.ini file. You can find out the location of the file from your PHP Info page. In our case, it resides at C:\MAMP\conf\php7.1.5\php.ini
Open this file with an editor like Notepad or VS Code. We are looking for the line that is commented out that would load xdebug. It should look like this:
Simply remove the semi-colon from the beginning of that line so that the next time PHP is initialized, it will load the Xdebug library.
We also need to add a couple of lines to the file for some Xdebug configuration. Add the following:
xdebug.remote_enable = 1
xdebug.remote_autostart = 1
In Visual Studio Code, navigate to the Extensions pane and search for PHP Debug. Install it and activate it.
To start debugging, and navigate to the Debugging tab in VS Code.
Next, Press the gear icon to generate the launch.json file, which allows Visual Studio Code to start the XDebug debugging session. Make sure to choose PHP as the debug environment.
To start the debugging process you can press F5 or click the green arrow in the debugging tab.
You can set breakpoints in your source code by selecting a line and pressing F9, or by clicking to the left of a line number.
If you now load the specific web page, Visual Studio Code will break into your source code at the specified break point. You’ll then get information about variables, call stack, etc. in the left hand pane.