VSCode + XDebug + WPLocal

Just ‘WORKS’ in VSCode

xDebug is an invaluable tool to have for debugging PHP, but it can be tricky to set up. Luckily, VS Code makes it easy to configure xDebug, and in my case it just works.

You only need to install the PHP Debug extension and reload the editor. You can then go to the “Run” tab and click “create a launch.json file” to create a new PHP debug configuration.

more steps below …..

Debug JS

Debugging PHP is only half the problem – we also need to be able to debug JavaScript. Since I use Mozilla Firefox as my main browser, I installed the Debugger for Firefox extension which integrates VS Code with Firefox.

Next, you’ll need to edit the *.code-workspace add some config for JS:

more steps below …..
BasicVSCode w/ WordPressWhat is XDebugXDebug in LocalWPXDebug VSCODEPHPStorm w/ WordPress

https://deliciousbrains.com/vs-code-wordpress/

Basic Setup for WordPress Development

Most of the time when coding in WordPress, you’ll either be working on a plugin or a theme. One way to do this might be to open that plugin or theme in your IDE and start coding away. There is a better way though, with the help of VS Code “Workspaces”.

You can think of a Workspace in VS Code as a container for your project – it not only includes your project, but it can include files that your project relies on (your WordPress installation), and any extensions or settings specific to that project.

I like Workspaces because you can create one of them for each project and change any setting or extension in VS Code at the Workspace level. For example, you may not want to use the WordPress Coding Standards on all of your projects, or maybe you work with a team of developers that can’t agree on tabs vs. spaces.

In my case, the vast majority of my time is spent on plugin development. So I’ll have a Projects folder that has all of the plugins I work on, and a Sites folder that contains all of my sites. I’ll then symlink the plugin I’m working on into a fresh WordPress website in the Sites folder.

In Visual Studio Code, I’ll first open the plugin itself, and then I’ll add the WordPress site by selecting File -> Add Folder to Workspace. That sets up a new Workspace where I can edit the plugin and the WordPress installation at the same time.

This is handy for quick edits to the wp-config.php file, and keeping an eye on the debug.log file while I’m developing.

Next, click File -> Save Workspace As to save that Workspace. This creates a *.code-workspace file that you can use to open your Workspace again in the future, and also serves as a config file that will come in handy later.

#Deeper PHP and WordPress Integration

With that out of the way, let’s take a look at how we can make Visual Studio Code and WordPress play a bit nicer. Out-of-the-box, VS Code doesn’t support WordPress and PHP as well as some other IDEs like PhpStorm (Find out how some of our team uses PhpStorm for WordPress Development). Luckily, that’s easy to change by installing some extensions.

Since WordPress is still mostly PHP, I use the PHP Intelephense extension, which adds PHP auto-completions, symbol navigation support, and a much better way to find references in your workspace.

While that will add auto-completions for PHP core functions and anything that you have defined in your project, it won’t pick up on much from WordPress core. For that there is the WordPress Snippet extension, which will autocomplete WordPress core functions, classes, and constants. It even will add WordPress function argument type hints, which often helps save a trip to the docs.

These tools make it much easier to work with WordPress plugins and themes, and PHP development in general.

#Debugging PHP

xDebug is an invaluable tool to have for debugging PHP, but it can be tricky to set up. Luckily, VS Code makes it easy to configure xDebug, and in my case it just works.

You only need to install the PHP Debug extension and reload the editor. You can then go to the “Run” tab and click “create a launch.json file” to create a new PHP debug configuration.

Create launch.json for xDebug

You should then see a pop-up towards the top of your editor asking you to select a Workspace folder to create the configuration in:

Select workspace for launch.json

Select “workspace” to insert the new configuration into your *.code-workspace file, and then “PHP” to add a PHP configuration. This will add some debug config to that file, including the new “Listen for XDebug” option. You can edit the name of the configuration or change the XDebug port here.

 

{
    "name": "Listen for XDebug",
    "type": "php",
    "request": "launch",
    "port": 9000
},

In my case, it also added a “Launch currently open script” config as well. With WordPress, we rarely need to load a PHP file directly, so I just deleted that config.

That’s it! You should be able to start debugging PHP from here. Head over to a PHP file in your WordPress plugin or theme, and click to the left to a line number to add a breakpoint to that line.

Setting a breakpoint in VS Code

When you head back over to the “Run” tab, select “Listen for XDebug” from the dropdown and click the play icon to start listening for requests. When your code hits that breakpoint, the runtime should pause and you can see all variables, the call stack, and more. Who knew debugging WordPress in Visual Studio Code could be so easy?

#Debugging JavaScript

Debugging PHP is only half the problem – we also need to be able to debug JavaScript. Since I use Mozilla Firefox as my main browser, I installed the Debugger for Firefox extension which integrates VS Code with Firefox.

Next, you’ll need to edit the *.code-workspace add some config for JS:

 

{
    "name": "Listen for JS",
    "type": "firefox",
    "request": "launch",
    "url": "http://yoursite.dev",
    "webRoot": "/path/to/your/site/root",
}

Once that’s been added, you should see the Listen for JS option in the debug drop down:

Listen for JS debug option

For reference, here’s my entire mdb.code-workspace file so far:

 

{
"folders": [
    {
    "path": "wp-migrate-db-pro"
    },
    {
    "path": "/Users/mattshaw/Sites/mdb/app/public"
    }
],
"launch": {
    "version": "0.2.0",
    "configurations": [
    {
        "type": "firefox",
        "request": "launch",
        "name": "Listen for JS",
        "url": "http://mdb.test",
        "webRoot": "/Users/mattshaw/Sites/mdb/app/public"
    },
    {
        "name": "Listen for XDebug",
        "type": "php",
        "request": "launch",
        "port": 9000
    }
    ]
}
}

Gotchas

If you’re using something like Webpack to bundle your JS files together, you may notice that your breakpoints aren’t working. You can use the sourceMapPathOverrides param in your *.code-workspace file to manually map the file paths correctly, but Debugger for Firefox has an easier solution.

If the debugger detects that the file you created a breakpoint in wasn’t loaded during a Firefox request, you should see the following prompt:

Debugger for Firefox Path Mapping Wizard

Simply click “Yes” to let the Path Mapping Wizard figure out the correct path for you. I’ve never been more grateful to such an obscure wizard in my life.

With that in place, it’s now easy to debug JS from within VS Code, using the same UI that is used for xDebug:

Debugging JS in VS Code

#Other Tips

I’ve come across some other important extensions that have been helpful in day-to-day development. The Git Lens extension adds simple git blame annotations to the line that you’re currently working on. This single line annotation of git blame works noticeably faster than PhpStorms’ implementation, which tries to run on the whole file at once. Unfortunately, it doesn’t have a GitHub integration, but even without it I still feel that it’s handy enough to keep around.

The PHP DocBlocker extension is super helpful for, well, docblocking. Simply type /** above a function, method, or class and it will autocomplete the docblock based on the function/method parameters.

The Prettier extension is great for cleaning up your CSS, JS, and HTML code on editor save.

If you work with a lot of modern JS it’s also worth installing the Babel ES6/ES7 extension, which adds syntax highlighting for ES6/ES7. I also have the Instant Markdown plugin installed, which I used to write this post and is a cool way of previewing your markdown in the browser.

#Closing Thoughts

After using it for three years, I still love VS Code. It’s like it took my favorite features of PhpStorm and Sublime Text, and combined them to create the perfect IDE (see how it beats out other PHP IDE/Editors for WordPress development in our comparison). I also really like the way that you can install extensions directly from within VS Code, and view the docs for that extension without leaving the editor.

Using XDebug

https://deliciousbrains.com/xdebug-advanced-php-debugging/

You could just debug your PHP code using dump debugging functions such as error_log, print, and var_dump, and let’s be honest, we’ve all done it a lot! While helpful sometimes, they often just aren’t enough and can actually slow you down while developing. There must be a better way, surely?!

Enter Xdebug, the rather awesome step debugging and profiling tool for PHP.

In this post, I’m going to take you through my Xdebug journey, and show you how to use it to make your life easier. You can thank me later (in the comments)

If you’re the type of person who prefers to learn things visually, Jonathan, our developer educator, has made a short video detailing how to use Xdebug with PHPStorm.

 

#How Xdebug Changed My Life

A few years ago I didn’t know debuggers existed, had never heard of Xdebug, and was quite happy using a function I’d cobbled together pinched from Stack Overflow in all my WordPress sites for debugging:

 

if ( ! function_exists( '_log' ) ) {
    function _log( $message ) {
        if ( WP_DEBUG === true ) {
            if ( is_array( $message ) || is_object( $message ) ) {
                error_log( print_r( $message, true ) );
            } else {
                error_log( $message );
            }
        }
    }
}

It was all I thought I needed until someone introduced me to Xdebug, and my life changed. Excuse the hyperbole, but it happened!

When you are dump debugging using functions like error_log or var_dump, you only output the variables you define, which might not be what you need. For example, while troubleshooting some code, you add the function somewhere to debug a variable. You refresh your page, so the debug line is executed, and then check your error log to look at the output. If this doesn’t give you any insight into the cause of the problem at hand, then you need to go back and add more debug lines to the code. Rinse and repeat.

Xdebug allows you to break during code execution and inspect all the variables in scope during a request. What this means is you have everything you need to troubleshoot during only one iteration of this cycle. You save a tremendous amount of time when tracking down issues, and your development workflow is more efficient.

#Troubleshooting++ with Xdebug

Xdebug really shines when trying to troubleshoot a problem whose cause is utterly unknown to you. If you know your function is broken, logging lines inside it is great and works well. But strange problem-causing behavior could be coming from anywhere in a project, like a plugin or WordPress core itself. How the hell do you track that down?

By using breakpoints, you can pause the code execution at any point, which means the best thing to do is to break early and follow the code execution through with Xdebug (more on that later) until you spot something gone awry. To save time, you can progressively move breakpoints further along in the execution until you get closer to the potential issue, instead of breaking on code already analyzed as not the cause of the problem. When you find the issue, you can change the values of variables on the fly after they are assigned, so you can test potential fixes while debugging, all during the same request.

#Debug Driven Development

Another great use of Xdebug is using it proactively during development instead of reacting to existing code issues. Think of this like Test-Driven Development (TDD) but using the debugger first instead of writing tests. I’m not even sure if Debug Driven Development (DDD) is a widely used term, but for me, I’ve used Xdebug to help me write new code in a couple of ways:

  1. Inspect existing arrays, objects, and class instances to find the data available to me in code, so I can use it in new code I write
  2. Immediately debug a newly-written piece of code to test it is working as expected

This isn’t something I do all the time, but Xdebug gives me this insight when I need it.

#Installing Xdebug

Hopefully the benefits I’ve detailed have got you wanting to use Xdebug and you’re ready for some installation steps. I’ve put together a list of the most common local environments with some handy links to getting Xdebug installed on them:

Matt Stauffer also recently compiled a list of popular configurations available, so if I’ve missed it, you should find something for your local environment there.

Do you work with a different local environment and need some guidance? Let us know in the comments.

#Xdebug Version 3

In November 2020, Xdebug 3 was released. Besides massive performance improvements and PHP 8 support, the most significant change was how you turn on Xdebug functionality through the new mode setting. In addition to making it easier to enable different types of debugging modes, it also changes how you configure Xdebug in your php.ini in the first place.

The online tutorial you’re following to install and configure Xdebug for your local development environment will determine which settings you need to configure. Fortunately, an Xdebug help doc on upgrading from version 2 to version 3 exists to guide you.

As a quick example, if you have version 2 installed, you might be instructed to configure your php.ini settings to look something like this:

 

[xdebug]
zend_extension="/path/to/xdebug/extension/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=127.0.0.1
xdebug.remote_port="9000"

Whereas if you have version 3 installed, you would need to configure it like this:

 

[xdebug]
zend_extension="/path/to/xdebug/extension/xdebug.so"
xdebug.mode=debug
xdebug.client_host=127.0.0.1
xdebug.client_port="9003"

In version 3, you can also enable different Xdebug modes by specifying them in a comma-separated list.

 

xdebug.mode=develop,trace

For this article, I’m using Xdebug 3, with the mode set to debug, but we’ll also cover any differences for version 2.

#PhpStorm Integration

News flash: I love PhpStorm! And guess what? PhpStorm has an awesome integration with Xdebug and their help docs include a complete set up guide.

If you don’t use PHPStorm, most other Integrated Development Environments (IDEs) like Visual Studio Code and editors like Sublime Text can be configured to use Xdebug.

#Start Debugging

Once you’ve installed Xdebug and configured PhpStorm, you can start interactively debugging your code. This is done by setting breakpoints at certain lines of your code and telling PhpStorm to listen for incoming connections. When PHP executes a line that has a breakpoint on it, Xdebug will step in and pause execution, allowing you to gain valuable insight into all that is happening during execution:

PhpStorm Xdebug debugging panel

The sidebar of the debug panel has various buttons for controlling the execution of the code. Here they are top-down as they appear in the screenshot:

  • Resume Program – continue with the PHP execution
  • Pause Program – not available during debugging
  • Stop – halt the execution
  • View Breakpoints – bring up a window of all the breakpoints set in all files of the project
  • Mute Breakpoints – deactivate the breakpoints during execution (good for just finishing the request without breaking any further)
  • Settings – tweak the debugger display
  • Pin Tab – always show the Debug panel

Next to the Debugger, Console, and Output tabs, the top bar of the panel controls how the debugger traverses the code so you can inspect different parts of the codebase:

  • Show Execution Point – jumps back to where the program is broken
  • Step Over – execute and move to the next line of the file
  • Step Into – if the next line has one or more functions, move the debugger into those to step through
  • Force Step Into – step into a function that is marked as skipped
  • Step Out – move the debugger out of the current function back to the function that called it
  • Run to Cursor – execute all the way to the line the cursor is on
  • Evaluate Expression – execute PHP while the debugger is running (think of this like Chrome’s JS console)
  • Show user-defined constants – toggles the display for any PHP constants your code has defined
  • Show Values Addresses – toggles the display of the memory address of objects
  • Show Empty Superglobals Variables – toggles the display of any empty superglobals
  • Add Method to Skip List – mark method to be skipped next time

Most of these buttons also have keyboard shortcuts, but the most frequently used are:

  • F9 – Resume Program
  • F8 – Step Over
  • F7 – Step Into

Breakpoints are added by clicking in the left-hand gutter of the code, along the line you want at which you want to break. PhpStorm also allows you to set conditional breakpoints, where you add PHP logic to control when a breakpoint actually fires:

PhpStorm add conditional breakpoint

When troubleshooting, it is often helpful to inspect and watch a variable’s value all the way through the execution of a request to see when it changes. PhpStorm allows you to add variables to a list that it watches and displays in a separate “Watches” panel, separate from all the data in the main “Variables” panel. You can watch a variable by either right-clicking the variable in the file during debugging and selecting Add to Watches or doing the same from the variable in the “Variables” panel:

PhpStorm add variable to watch list

Watches are not limited to variables, however. You can even add expressions or functions to your watch list. This is extremely useful when you’re working with a CMS like WordPress, which makes use of many helper functions like site_url() or get_post(). By adding the full function call to your watch list, and you’ll always be able to see what the result of that function will be.

#Stack Trace

In Xdebug version 2, enabling Xdebug would enable the extended stack trace for any errors, notices, or warnings written to the PHP log. With the release of version 3, this was changed so that it needs to be explicitly enabled by setting the Xdebug mode to develop.

Because I rely on wp-content/debug.log or the PHP error_log to alert me to issues, but I use PhpStorm to see the stack trace, I don’t enable the extended (and very noisy) stack trace. When I used version 2 of Xdebug I disabled the stack trace in the log by putting this in my wp-config.php file:

 

if ( function_exists( 'xdebug_disable' ) ) {
    xdebug_disable();
}

#Advanced Use

Mastered the basics? Ready for more? Here are some advanced ways you can use Xdebug to improve your development workflows.

#Profiling

When you really need to investigate performance issues with your code or website, one of the best tools we’ve found is Blackfire, which we’ve written about before. But Xdebug also profiles for you and PhpStorm can interpret the results, which is great as it means you never have to leave PhpStorm! 😂 To enable the profiler, edit your php.ini file to add or uncomment these lines in the Xdebug section:

Version 3

 

xdebug.mode = profile
xdebug.output_dir = "/path/to/desired/profiler/output/directory"

Version 2

 

xdebug.profiler_enable=1
xdebug.profiler_output_dir="/path/to/desired/profiler/output/directory"

Then Xdebug will create a profile log file in the output_dir or profiler_output_dir you specify for each execution of your code. Remember to disable the profiler when you’re done, so you don’t fill your hard drive with log files! Alternatively, set the output directory to the /tmp directory for your OS. These logs can then be analyzed in PhpStorm by navigating to Tools > Analyze Xdebug Profiler Snapshot and selecting the log file. The visualization isn’t as in-depth as Blackfire or using something like KCachegrind, but it is still is a great way to analyze bottlenecks in your code:

Analyzing Xdebug profile log in PhpStorm

#Remote Debugging via SSH

You can troubleshoot bugs only if you can recreate them on your development environment. Of course, when it comes to running a website, we recommend having your development environment as close to production as possible, and you debug on a near-as-possible copy of the production database. Still, sometimes bugs and oddities will only happen on production. No one wants to start messing around on a live site, editing files to add logging lines. Don’t worry, PhpStorm and Xdebug have you covered! You can install Xdebug on a remote server and debug the code execution locally using Xdebug and PhpStorm. This feature is a lifesaver and doesn’t require much to set up. Make sure to turn off Xdebug when you are finished, so your site’s performance isn’t impacted by Xdebug unnecessarily.

#Is Xdebug the Only Way to Debug PHP for WordPress?

The short answer is ‘no’, the long answer is ‘it depends’. While Xdebug is the recommended way to enable step debugging for PHP, you may want to consider other options. One which crossed my path recently is Ray, from the folks at Spatie. Ray is a paid application that runs on Mac, Windows or Linux, and connects to your PHP project. This is done either through a composer package or a WordPress plugin if you’re debugging for WordPress.

Once you have everything set up, you can use the ray() function call, which is very similar to JavaScript’s console.log() method, to send any arbitrary data to the Ray application. You can send it simple strings, variables (including arrays and objects), and even multiple data combinations.

 

ray('Hello world');

ray('My variable', $variable);

ray('array', $array, 'object', $object);

Ray sends this data to the Ray application using a similar process as you might do when making a cURL request to a JSON HTTP API.

There are some advantages to using Ray over Xdebug. Because Ray will only transmit data from your code to the Ray application when the application is running, it won’t have as much effect on your system performance as Xdebug might. Xdebug 3 is quite a performance improvement over Xdebug 2, and you can turn off debugging via the browser extension when you need to. It is, however, still installed and active on your local PHP environment, so you can only really turn it off entirely by disabling it in your php.ini.

Ray also allows you to do more advanced things like the ability to pause code execution, remote debugging via SSH, and the ability to capture any queries being executed during a PHP request. Xdebug does quite a bit more and is free, but Ray is something to consider as an option for debugging, especially if you’re still relying on dump debugging during development.

#Supporting Xdebug

The person behind Xdebug is Derick Rethans. He is the sole developer of Xdebug and relies on sponsors to fund his ongoing work on maintenance and updates to Xdebug. Here at Delicious Brains, we’ve been a Patreon supporter of his since February 2019. If you or your company finds Xdebug useful, why not sponsor him through his Patreon or via GitHub?

#Conclusion

I hope this has been a good introduction to how powerful and valuable using a debugger like Xdebug is for your development workflow, as well as a possible alternative if you find it too complex. Xdebug is a huge time saver, and I couldn’t imagine developing without it in my toolbox. Do you use Xdebug, Ray, or another debugger? Have I missed any excellent features, or do you have any tips? Let me know in the comments below.

https://localwp.com/help-docs/advanced/using-xdebug-within-local/

Using Xdebug within Local

What is Xdebug?

Xdebug is an extension for PHP that helps you with debugging and developing applications.

You’ve probably already run into Xdebug and not been aware of it. The most obvious improvements are:

  1. Improved formatting of the var_dump() PHP function.
  2. More informative notices, warnings, and errors.

Because Xdebug does include more information about what is happening when things go wrong, it’s often enabled in development environments like Local.

The above improvements are awesome, but Xdebug also includes a powerful step debugger that is essential for debugging the most complex issues of a PHP project.

Xdebug Features

Let’s take a closer look at the main features of Xdebug and how we can make use of them within Local and WordPress.

Improvements to var_dump()

The easiest way to dive into an issue and see what’s happening is by using PHP’s var_dump(). Sure, it’s a little hacky to do, but it’s also quick and, more often than not, enough to get you what you need.

Without Xdebug, you have to remember to format PHP in a specific way. When Xdebug is enabled, calling var_dump() produces output that’s both readable and useful.

A screenshot showing the difference in var_dump output between having Xdebug enabled and having Xdebug disabled.When Xdebug is enabled, the output of var_dump()is more structured and easier to read.

Better Notices, Warnings, and Errors

When troubleshooting, one of the most helpful things is to get an idea of where exactly an error is occurring. Xdebug will improve the messages that PHP gives by providing a stack trace. You can think of a stack trace as a list of functions called before the error was encountered.

A screenshot showing the difference in PHP messages between having Xdebug enabled and having Xdebug disabled.The same breaking code (calling a non-existent function) displays differently depending on if Xdebug is enabled or not.

NOTE

If you’re still new to doing PHP development, this “feature” of Xdebug can be confusing. You might be asking yourself:

 

“Why does my site look broken in Local but not on Production?”

 

In some cases, this is because Xdebug enhances these messages (notices, warnings, errors) to make them more “noisy.”

 

To learn more about this as well as how to configure PHP messages in Local, see the related Help Doc:

 

 

Step Debugger

Often, when people think of Xdebug, the step debugger is what comes to mind. This feature allows you to interactively walk through your code and inspect the application’s state at specific points in time.

Each of those points in time is specified by creating a “breakpoint” within the editor. The editor communicates with Xdebug to pause the application at that specific point in the code.

Using Xdebug’s step debugger with VS Code to investigate the call stack and variables within WordPress’ default TwentyTwentyOne theme header.

Traditionally it’s been challenging getting Xdebug and your editor of choice to communicate with each other. Local has two Add-ons that help make that configuration process easy; one for PHPStorm and one for VS Code.

img

Step Debugger Local Addon: Xdebug + VS Code

This Local Add-on helps to configure the connection between Xdebug and VS Code. For more information or to help with development, take a look at these links:

img

Step Debugger Local Addon: Xdebug + PHPStorm

This Local Add-on helps to configure the connection between Xdebug and PHPStorm. For more information or to help with development, take a look at these links:

Other Editors

If you have a different editor, you may still be able to use Xdebug’s step debugger within Local. I recommend taking a look at Xdebug’s documentation for specific setings:

Each site’s PHP configuration can be found within the site folder within the PHP.ini file for the site, which can be found in the conf folder:

site-name/conf/php/php.ini.hbs

Make sure to restart the site after any changes to this file so that Local can re-compile those settings for the site.

 

https://marketplace.visualstudio.com/items?itemName=felixfbecker.php-debug

If you find this extension usefull, if it helps you solve your problems and if you appreciate the support given here, consider sponsoring our work.

Installation

Install the extension: Press F1, type ext install php-debug.

This extension is a debug adapter between VS Code and Xdebug by Derick Rethans. Xdebug is a PHP extension (a .so file on Linux and a .dll on Windows) that needs to be installed on your server.

  1. Install Xdebug *I highly recommend you make a simple test.php file, put a phpinfo(); statement in there, then copy the output and paste it into the Xdebug installation wizard. It will analyze it and give you tailored installation instructions for your environment.* In short:

    • On Windows: Download the appropriate precompiled DLL for your PHP version, architecture (64/32 Bit), thread safety (TS/NTS) and Visual Studio compiler version and place it in your PHP extension folder.
    • On Linux: Either download the source code as a tarball or clone it with git, then compile it.
  2. Configure PHP to use Xdebug by adding zend_extension=path/to/xdebug to your php.ini. The path of your php.ini is shown in your phpinfo() output under "Loaded Configuration File".

  3. Enable remote debugging in your php.ini:

    For Xdebug v3.x.x:

    xdebug.mode = debug
    xdebug.start_with_request = yes
    

    For Xdebug v2.x.x:

    xdebug.remote_enable = 1
    xdebug.remote_autostart = 1
    xdebug.remote_port = 9003
    

    There are other ways to tell Xdebug to connect to a remote debugger, like cookies, query parameters or browser extensions. I recommend remote_autostart (Xdebug v2)/start_with_request (Xdebug v3) because it "just works". There are also a variety of other options, like the port, please see the Xdebug documentation on remote debugging for more information. Please note that the default Xdebug port changed between Xdebug v2 to v3 from 9000 to 9003.

  4. If you are doing web development, don't forget to restart your webserver to reload the settings.

  5. Verify your installation by checking your phpinfo() output for an Xdebug section.

VS Code Configuration

In your project, go to the debugger and hit the little gear icon and choose PHP. A new launch configuration will be created for you with three configurations:

  • Listen for Xdebug This setting will simply start listening on the specified port (by default 9003) for Xdebug. If you configured Xdebug like recommended above, every time you make a request with a browser to your webserver or launch a CLI script Xdebug will connect and you can stop on breakpoints, exceptions etc.
  • Launch currently open script This setting is an example of CLI debugging. It will launch the currently opened script as a CLI, show all stdout/stderr output in the debug console and end the debug session once the script exits.
  • Launch Built-in web server This configuration starts the PHP built-in web server on a random port and opens the browser with the serverReadyAction directive. The port is random (localhost:0) but can be changed to a desired fixed port (ex: localhost:8080). If a router script is needed, add it with program directive. Additional PHP/Xdebug directives trigger debugging on every page load.

More general information on debugging with VS Code can be found on https://code.visualstudio.com/docs/editor/debugging.

Supported launch.json settings:
  • request: Always "launch"

  • hostname: The address to bind to when listening for Xdebug (default: all IPv6 connections if available, else all IPv4 connections)

  • port: The port on which to listen for Xdebug (default: 9003). If port is set to 0 a random port is chosen by the system and a placeholder ${port} is replaced with the chosen port in env and runtimeArgs.

  • stopOnEntry: Whether to break at the beginning of the script (default: false)

  • pathMappings: A list of server paths mapping to the local source paths on your machine, see "Remote Host Debugging" below

  • log: Whether to log all communication between VS Code and the adapter to the debug console. See Troubleshooting further down.

  • ignore: An optional array of glob patterns that errors should be ignored from (for example **/vendor/**/*.php)

  • xdebugSettings
    

    : Allows you to override Xdebug's remote debugging settings to fine tuning Xdebug to your needs. For example, you can play with

    max_children
    

    and

    max_depth
    

    to change the max number of array and object children that are retrieved and the max depth in structures like arrays and objects. This can speed up the debugger on slow machines. For a full list of feature names that can be set please refer to the

    Xdebug documentation

    .

    • max_children: max number of array or object children to initially retrieve
    • max_data: max amount of variable data to initially retrieve.
    • max_depth: maximum depth that the debugger engine may return when sending arrays, hashs or object structures to the IDE (there should be no need to change this as depth is retrieved incrementally, large value can cause IDE to hang).
    • show_hidden: This feature can get set by the IDE if it wants to have more detailed internal information on properties (eg. private members of classes, etc.) Zero means that hidden members are not shown to the IDE.

Options specific to CLI debugging:

  • program: Path to the script that should be launched
  • args: Arguments passed to the script
  • cwd: The current working directory to use when launching the script
  • runtimeExecutable: Path to the PHP binary used for launching the script. By default the one on the PATH.
  • runtimeArgs: Additional arguments to pass to the PHP binary
  • externalConsole: Launches the script in an external console window instead of the debug console (default: false)
  • env: Environment variables to pass to the script

Features

  • Line breakpoints
  • Conditional breakpoints
  • Function breakpoints
  • Step over, step in, step out
  • Break on entry
  • Breaking on uncaught exceptions and errors / warnings / notices
  • Multiple, parallel requests
  • Stack traces, scope variables, superglobals, user defined constants
  • Arrays & objects (including classname, private and static properties)
  • Debug console
  • Watches
  • Run as CLI
  • Run without debugging

Remote Host Debugging

To debug a running application on a remote host, you need to tell Xdebug to connect to a different IP than localhost. This can either be done by setting xdebug.remote_host to your IP or by setting xdebug.remote_connect_back = 1 to make Xdebug always connect back to the machine who did the web request. The latter is the only setting that supports multiple users debugging the same server and "just works" for web projects. Again, please see the Xdebug documentation on the subject for more information.

To make VS Code map the files on the server to the right files on your local machine, you have to set the pathMappings settings in your launch.json. Example:

// server -> local
"pathMappings": {
  "/var/www/html": "${workspaceFolder}/www",
  "/app": "${workspaceFolder}/app"
}

Please also note that setting any of the CLI debugging options will not work with remote host debugging, because the script is always launched locally. If you want to debug a CLI script on a remote host, you need to launch it manually from the command line.

Troubleshooting

  • Ask a question on StackOverflow
  • If you think you found a bug, open an issue
  • Make sure you have the latest version of this extension and Xdebug installed
  • Try out a simple PHP file to recreate the issue, for example from the testproject
  • In your php.ini, set xdebug.remote_log = /path/to/logfile (make sure your webserver has write permissions to the file)
  • Set "log": true in your launch.json

Contributing

To hack on this adapter, clone the repository and open it in VS Code. You need NodeJS with NPM installed and in your PATH. Also a recent PHP and Xdebug should be installed and in your PATH.

  1. Install NPM packages by either running npm install on command line in the project directory or selecting Terminal / Run Task... / npm / npm: install in VS Code menu.
  2. Run the build/watch process either by running npm run watch on command line in the project directory or selecting Terminal / Run Build Task... in VS Code menu.
  3. Start the debug adapter by opening the Run and Debug side bar, selecting Debug adapter configuration and clicking on the green Run arrow (or hitting F5). The compiled adapter will be running in "server mode" and listening on TCP port 4711.
  4. Run a separate instance of VS Code, called "Extension Development Host" by running code testproject --extensionDevelopmentPath=. on command line in the project directory or selecting the Launch Extension Run and Debug configuration and pressing the green Run arrow. Another shortcut is to run npm run start. You can also run an Insiders build of VS Code for testing newer features.
  5. In the "Extension Development Host" instance open .vscode/launch.json and uncomment the debugServer configuration line. Run your PHP debug session by selecting the desired configuration and hitting F5. Now you can debug the testproject like specified above and set breakpoints inside your first VS Code instance to step through the adapter code.

More on testing extensions can be found on https://code.visualstudio.com/api/working-with-extensions/testing-extension.

Tests are written with Mocha and can be run with npm test or from Terminal / Run Task... / npm: test. When you submit a PR the tests will be run in CI on Linux, macOS and Windows against multiple PHP and Xdebug versions.

Before submitting a PR also run npm run lint or Terminal / Run Tasks... / npm: lint

BONUS – PHPSTORM with WordPress

https://deliciousbrains.com/how-we-use-phpstorm-wordpress-development/#xdebug

Many of the Delicious Brains team use PhpStorm, the PHP IDE from JetBrains, as their go-to code editor, development environment, and all-round PHP best friend.

Some on the team swear by using a lean and fast code editor like Sublime Text and Visual Studio Code, and would find PhpStorm much slower, larger and possibly daunting to use. However, as an integrated development environment, PhpStorm offers so much more than just editing code.

In this article, I will walk you through some of the features that make it great for WordPress development and show you why I, and many others, love it.

#WordPress Integration

PhpStorm comes packed with very neat WordPress support which makes using PhpStorm for WordPress theme, plugin, and site development even easier. A complete rundown of the new WordPress features can be found here.

PhpStorm recognizes a WordPress related project and will ask you to point it in the direction of your installation path. It will also check to see if you want to add the installation to the PHP Include paths:

Include Path to WordPress in PHPStorm

This will enable the IDE to fully understand the WordPress codebase giving you some excellent benefits. If your wp-content directory is outside of the installation path, you may want to also add that as an extra ‘included path’, to allow indexing of plugin and theme files.

#Hooks Support

PhpStorm’s indexing of the WordPress codebase really supercharges the use of action and filter hooks. This is probably my favourite feature and it comes in a number of parts.

Do you find yourself copying the callback function name of a hook and using it to find the function declaration in your codebase? No more my friend, no more. Simply CMD+Click (Ctrl+Click on Windows/Linux) on the callback:

PHPStorm Hook callback navigation

Have you ever hooked a function to a WordPress core action or filter and wondered where that code will get executed? Previously that meant doing another search of the codebase, but now just click on Hook Invocation in the left gutter next to the hook, et voilà:

PHPStorm Hook invocation navigation

#Code Completion of Hooks

There are so many action and filter hooks in the WordPress codebase that I find myself frequently checking the Code Reference for the correct naming. This is now taken care of with the new code completion of action and filter names.

If your wp-content directory is in a different location to the WordPress core files, you can add it as an extra include path so that hooks and filters for plugins and themes are indexed also:

Hook name autocompletion in PHPStorm

#Search on WordPress.org

Talking of the WordPress Code Reference, have you ever wanted to look at the documentation for a WordPress function? Now this is super simple by highlighting the function and selecting ‘Search on WordPress.org’ from the context menu:

Performing a quick WordPress hook search in PHPStorm

Searching for where a hook is registered in WordPress? You can do this quickly within PhpStorm using ‘Navigate to Symbol’. Simply use CMD-ALT-O (Ctrl+Alt+Shift+N on Windows/Linux) and enter the name of the hook to find:

Navigate to specific hook in PHPStorm

#Code Style

Here at Delicious Brains, we are big on developing with the WordPress coding standards in mind and the next couple of PhpStorm features make this much easier to integrate into our development workflow.

PhpStorm allows you to define coding styles for the languages you are developing with. It now comes with a WordPress-specific style that helps you automatically format your code to the coding standards (check out ‘Code > Reformat Code’).

We have forked the style with a few tweaks of our own. Feel free to use and let us know if you find any issues.

#PHP Code Sniffer

Code styles are great for formatting code to standards, but the standards are more than just formatting, as they define rules about how the code should be written. PhpStorm allows you to integrate easily with PHP Code Sniffer to detect any issues with your code against the WordPress coding standards, defined by the WordPress PHP Sniffer rules.

An installation guide for both PHP Code Sniffer and the WordPress rules can be found on the PhpStorm help site.

Code sniffing is about prevention instead of a cure, and the integration in the PhpStorm editor alerting you to issues is extremely helpful. Once you have it all installed, you will instantly start to receive feedback on any issues in your code:

PHP Sniffer in action

#Development Tools

PhpStorm is stacked with lots of non-WordPress specific features that are great for modern development practices, but there are too many to mention here. Let me take you through some of my favourites.

#WP-CLI

PhpStorm offers great built-in support for WP-CLI for frequent users of command-line tools. It gives you a quick overview of available arguments as you’re typing, eliminating the need of having to look through the documentation for a list of supported arguments, once you configure it. The feature I love the most is the autosuggestions, if you don’t remember the full command, PhpStorm gives you a list of possible commands based on your input.

PhpStorm WPCLI integration

#Xdebug

I can’t bring myself to remember a time when I debugged PHP without using Xdebug. It is the debugging and profiling extension for PHP, that allows you to literally step through your code as it executes to troubleshoot code, watch values, evaluate expressions, and much more. PhpStorm integrates seamlessly with Xdebug with minimal installation, giving you so much more insight than var_dump.

Once you have set a breakpoint, and your code has hit that point, you can really take a second and look under the hood. You can expand objects and arrays, view the stack trace, and in PhpStorm there is a lovely tooltip hover detail, which evaluates expression inline. Take a look at my quick demo of troubleshooting code with Xdebug:

As of December 2020, the content of this video is still accurate even though the PhpStorm UI is a bit out of date. We plan on updating the video in the future 🙂

 

We have a separate, more detailed article on advanced PHP debugging with Xdebug in PhpStorm as well as Visual Studio Code. Be sure to check those out if you want to dive deeper.

#Profiler

We’ve written about Xdebug Profiling before in PhpStorm, which includes a profiling tool, useful for debugging the performance of WordPress plugins, applications and processes. Although it is bundled with Xdebug, there are a few further steps to enable it with PhpStorm.

Once installed and turned on, you can run the process you want to profile and it will start capturing data, in the formatcachegrind.out.%p as defined in your php.ini. You can then open this capture in PhpStorm for analysis via ‘Tools > Analyze Xdebug Profiler Snapshot’. You will see something like the following, where you can view the execution stats of each function, sort functions by time taken and calls made, as well as drilling down into the call stack for the functions:

Analyzing an XDebug Profiler snapshot in PhpStorm

#Git & SVN

Although I can use Git and SVN in the command line, I like to use the Git & SVN integration in PhpStorm as it stops me from moving between the terminal or another program. The integration is pretty slick: auto detecting Git and SVN roots in your project, presenting a powerful file diff and merge UI, as well as displaying the version history of selections or whole files.

Since we have started to regularly contribute to WordPress core using SVN, I have found its ‘Apply’ and ‘Create’ patch features an invaluable timesaver. Simply select a patch file in your project and choose ‘Apply Patch’ from the context menu.

To create a patch from your changes, go to ‘VCS > Create Patch’, or for specific files select the file(s) in the ‘Local Changes’ tab of the ‘Version Control’ panel, and choose ‘Create Patch’:

Creating an SVN patch in PHPStorm

#GitHub

If your project has Git repositories registered with remotes that are hosted on GitHub, PhpStorm gives you a couple of really nice features. You can actually create a ‘Pull Request’ from inside the IDE. Pretty handy right? Once you have committed some code to a branch, go to ‘VCS > Git > Create Pull Request’:

Creating a GitHub pull request from PHPStorm

If you develop using the forking flow, or you contribute to open source repositories on GitHub, you will know what a hassle it is to keep your fork up to date with the master repo. PhpStorm handles this all for you, including adding an ‘upstream’ remote to your checked out fork. Go to ‘VCS > Git > Rebase My GitHub Fork’. Check out my quick demonstration video below:

The content of this video is still current as of December 2020. Nothing has changed when it comes to rebasing works within PhpStorm.

 

If you are a PhpStorm user then I hope you found something new and useful here. If not, then perhaps it convinced you to take a look? While PhpStorm might not be the best editor for many of you, we still find it very efficient in our workflow.

Over at Laracasts there is a great free series of videos on how to be awesome in PhpStorm which, although geared towards Laravel at times, is an excellent resource for developers using PhpStorm as you can apply the same practices for WordPress development.

What are your favorite features? Have I missed any you think are worth a mention? Let us know in the comments.

 

Scroll to Top