A green layered background showing the Xdebug logo, complete with a green 'X'.

How Xdebug Can Help You Become a Better WordPress Developer

Posted on

As any developer can attest, code isn’t prepared for manufacturing after the primary draft. One key a part of the event course of is debugging — eradicating or altering all elements of your code that don’t work.

The Xdebug extension for PHP is a well-liked strategy to root out and destroy the entire bugs in your code.

One of many nice elements of Xdebug is how versatile it’s. No matter your most well-liked framework or growth setting, you’ll have the ability to discover a model of Xdebug that slots into your workflow. From there, getting a deal with on the device received’t take lengthy.

This tutorial will take a look at Xdebug in depth, together with the set up course of, integrating it into your setup, and common utilization.

First, let’s provide you with extra context on what Xdebug is and what it does.

Introducing Xdebug

Xdebug is among the hottest extensions to debug your PHP code. You’ll set up it from inside your chosen setting, and it acts as a “step debugger.”

A green layered background showing the Xdebug logo, complete with a green 'X'.
The Xdebug emblem.

Briefly, this allows you to work in your code line by line so you possibly can step by way of and take a look at how the code acts and interacts inside your program, in addition to examine its output. From there, you can also make adjustments as you see match.

Xdebug can do rather more, although:

  • You possibly can analyze the performance of your code utilizing a set of metrics and visualizations.
  • If you run PHP unit assessments, you possibly can see which suites of code you run and execute.
  • Xdebug contains “tracing” capabilities, which is able to write each operate name to disk. This can embody arguments, variable assignments, and return values.
  • Xdebug additionally makes enhancements to the usual PHP error reporting. We’ll cowl extra on this later.

Given the characteristic set, there are many methods to make use of Xdebug (and any comparable debugger) inside your workflow. We’ll cowl these within the subsequent part.

Debugging is a key part of the development process- and Xebug is here to make that process easier 💪Click to Tweet

Why You’d Need To Use Xdebug

Many builders received’t have a devoted debugging workflow that makes use of third-party instruments and extensions. It is because PHP contains its personal rudimentary error logging. You’ll use instructions resembling error_log, var_dump, and print to see the outcomes of variables and performance calls.

For instance, there are many snippets you possibly can repurpose for WordPress growth — Stack Overflow is rife with them:

operate log_me($message) {
  if ( WP_DEBUG === true ) {
      if ( is_array($message) || is_object($message) ) {
          error_log( print_r($message, true) );
      } else {
           error_log( $message );
      }
  }
}

Nonetheless, there are some vital drawbacks to this method:

  • You first should make sure you allow error logs for the platform you’re working with. On this case, you’ll need to allow WP_DEBUG (extra on this shortly).
  • This instance of “dump” debugging provides much less scope for investigation than step debugging. Right here, you possibly can solely output no matter you outline.

The latter level requires a lot guide effort, particularly in case your day job isn’t as a sysadmin. For instance, if you wish to debug a code block, you may add your snippet primarily based on a variable you outline. Nonetheless, it won’t be the supply of the issue and even point out what’s taking place.

As a substitute, a device resembling Xdebug can work its magic to offer better scope:

  • You possibly can “break” your code at numerous factors through the execution to see what is going on in real-time.
  • There are myriad metrics, visualizations, branches, and extra that can assist you verify what your code is doing and the way it responds.
  • Typically, you possibly can even change values on the fly through the debugging course of. This provides immense worth, even for suites of code that work effectively. You possibly can basically perform guide unit assessments at any level.
  • Since you use breakpoints to mark up areas to debug, you don’t must work with snippets inside your code. This retains your code cleaner and reduces the variety of future points.

Total, utilizing a device resembling Xdebug is a proactive determination moderately than a reactive one. You should utilize step debugging as a part of the core growth course of, very similar to implementing unit assessments as a part of test-driven growth (TDD).

How To Flip On PHP Error Logging

When you might debug your code and not using a particular error, it’s usually good to know if a problem happens with out having Xdebug open. This provides you a starting point for exploration. It’s not strictly essential, however could be a useful a part of your chain.

To report each error that arises, you’ll want so as to add a line to the highest of the related PHP file:

error_reporting(E_ALL);

It is a catch-all command, and you may obtain the identical utilizing the ini_set operate:

ini_set('error_reporting', E_ALL);

This allows you to change settings inside your php.ini file on a project-by-project foundation. When you might go into this file and make a guide change, it’s usually a greater thought to work with ini_set to alter the precise parameter:

ini_set('display_errors', '1');

After you have energetic error reporting set to your liking, you possibly can start working with Xdebug.

How To Use Xdebug

Over the subsequent few sections, we’ll present you easy methods to use Xdebug, together with the steps you’ll must set issues up. Whereas we are able to’t cowl each device facet, this quick-start information will get you going quick.

First, although, you’ll want to set up Xdebug. Let’s learn how to do it.

1. Set up Xdebug for Your Working System (OS)

As a result of Xdebug is adaptable to any variety of setups, the exact process for each will probably be barely completely different. On the OS degree, there are a number of variations:

  • Home windows: It is a considerably difficult setup course of that includes utilizing an current PHP file and an installation wizard, then downloading the best model on your system.
  • Linux: The strategy right here is arguably essentially the most simple: You should utilize a package manager to put in Xdebug, or the PHP Extension Community Library (PECL).
  • Mac: This technique can also be easy: As soon as you put in PECL, you possibly can run pecl set up xdebug from a Terminal occasion. You’ll additionally must have XCode command line instruments and PHP put in in your system.

Nonetheless, most customers received’t need to keep on with a system-level occasion of Xdebug. As a substitute, you’ll need to combine it into your personal growth setting.

2. Combine Xdebug Into Your Improvement Surroundings

As soon as you put in Xdebug on your OS, it is best to join it to your setting.

There are such a lot of supported techniques and instruments right here that we are able to’t go into all of them. In a while, we’ll give you directions for each DevKinsta and PhpStorm. Even so, there are many different widespread environments to select from. Under are a few of our high suggestions.

Various Vagrant Vagrants (VVV)

VVV is among the named environments on the Make WordPress website:

A blue background containing 8-bit ASCII art of the Varying Vagrant Vagrants logo (
The Various Vagrant Vagrants emblem.

The excellent news is that VVV already features a version of Xdebug, however you’ll want to activate it. You are able to do this utilizing Safe Shell (SSH) inside a Terminal window:

vagrant ssh -c "switch_php_debugmod xdebug"

There’s somewhat little bit of a efficiency hit, although, and also you’ll want to show this selection again on when you provision your websites.

Laravel Valet

For some customers, Laravel’s Valet represents a near-perfect internet growth setting. Even higher, you possibly can combine Xdebug with it.

To do that, you’ll must create a configuration file for the debugger. You could find your personal path utilizing php --ini on the command line, which is able to return a number of completely different file paths:

A Terminal window showing a list of paths of .ini PHP configuration files, and an empty command prompt cursor.
The Terminal displaying an inventory of configuration file paths.

Subsequent, create a brand new xdebug.ini file on the path for extra .ini information. In our instance, it’s at /decide/homebrew/and so on/php/7.4/conf.d.

When you open this new file, additionally open the trail to the Loaded Configuration File (your foremost php.ini file). With each open, add the next to the underside:

  • php.ini: zend_extension="xdebug.so"
  • xdebug.ini: xdebug.mode=debug

When you’ve saved your adjustments, run valet restart from the Terminal, then add phpinfo(); exit; to certainly one of your web site’s information. You’ll need to test whether or not this works by way of a fast web page load inside the browser.

A PHP information file within the browser, showing the Xdebug logo and the
The PHP info display.

Observe that you could be must restart PHP utilizing sudo brew companies restart php in addition to test that your system set up of Xdebug is right utilizing php --info | grep xdebug. You’ll discover the Xdebug-specific traces inside the output:

A Terminal window showing a number of different Xdebug configuration settings (such as output names and display variables). The prompt shows the

From right here, you possibly can look to include Xdebug into your coding editor of selection.

XAMPP

Very like Valet, there are a number of elements to the method for XAMPP. Nonetheless, Home windows and macOS variations have two completely different processes.

Start by putting in XAMPP, then run a fast test to see if the php_xdebug.dll file (Home windows) or xdebug.so file (macOS) exists in your system:

A Terminal window showing a snippet to test whether a while exists. If it does, the Terminal will output
A Terminal window displaying a check for a XAMPP file.

If the file exists, you possibly can transfer on to the configuration. In any other case, you’ll first must download either the right binary for Home windows — a 64-bit file on your most well-liked PHP model — or set up a number of extra dependencies when you’re on a Mac.

For Home windows, rename the DLL file php_xdebug.dll, then transfer it to the xamppphpext file path. Subsequent, open the xamppphpphp.ini file in your preferred code editor and add the next:

output_buffering = Off

On the [XDebug] part, add the subsequent three traces:

zend_extension=xdebug
xdebug.mode=debug
xdebug.start_with_request=set off

When you save your adjustments, restart Apache and check for Xdebug.

For Mac, you’ll need to make sure you set up the Xcode command line instruments utilizing xcode-select --install at a Terminal occasion. After that, there are three packages you’ll need to set up utilizing Homebrew:

brew set up autoconf automake libtool

In some instances, you’ll additionally must reinstall XAMPP to get each the core program and the “Developer Information.” You need to have the ability to re-install solely these information, however you’ll need to perform a backup of your current setup first.

Subsequent, navigate to the obtain for the Xdebug supply folder in your system and unpack the TGZ file. Inside a Terminal window, navigate to that listing and run the next:

phpize
pecl set up xdebug

Observe that you could be want to make use of sudo right here too. From right here, you possibly can edit the XAMPP php.ini file. For many macOS installations, you’ll discover it at /Functions/XAMPP/xamppfiles/and so on/php.ini. Inside this listing, you’ll additionally discover the trail to your xdebug.so file — observe this down and use it instead of the file path placeholder for this snippet:

[xdebug]
zend_extension=/path/to/xdebug.so
xdebug.mode=develop,degug
xdebug.start_with_request=sure

To check whether or not this works, create a brand new xdebug_info.php file inside the principle htdocs XAMPP listing. Inside, add the next:

<?php
xdebug_info();

…then refresh Apache and check Xdebug within the browser.

Utilizing PhpStorm With Xdebug

As soon as you put in Xdebug by way of the OS and your growth setting, you’ll additionally must view the debugger itself. You’ll do that by way of your chosen code editor or integrated development environment (IDE). As together with your setting, there are such a lot of to select from, and each might need a special method.

That stated, many builders decide to make use of JetBrains’ PhpStorm. The truth is, PhpStorm provides “WordPress-aware assistance” — and it’s a preferred selection for a lot of different causes, too.

The PhpStorm interface, with a tree directory for the project on the left that uses white, blue, and yellow text. The right-hand side contains PHP code for a WordPress plugin, using orange, purple, green, and white text.
The PhpStorm interface.

The JetBrains website contains full directions on connecting Xdebug and PhpStorm, however we’ll assessment them right here.

First, navigate to the Languages & Frameworks > PHP web page inside the Preferences pane. Right here, open up the Extra Objects kebab menu subsequent to the CLI Interpreter dropdown area:

A partial PhpStorm Preferences screen, showing the page link (
Choosing a CLI interpreter in PhpStorm.

This can present some additional particulars about your PHP model and interpreter. If you happen to click on the Extra objects ellipsis subsequent to the Configuration file choice, you’ll see full paths on your php.ini file:

A partial PhpStorm More Items screen showing the name of the configuration, a path to the PHP executable file, the current PHP and debugger version numbers, and a list of configuration files for various aspects of the PHP installation.
Amending the PHP configuration inside PhpStorm.

You’ll be working with this PHP file subsequent to proceed the setup course of.

Working Inside the php.ini File

The primary process right here is to edit out any traces that impression how Xdebug will work with PhpStorm.

Inside the php.ini file, search for the next traces and both take away them or remark them out:

zend_extension=<path_to_zend_debugger>
zend_extension=<path_to_zend_optimizer>

These traces received’t be current in all instances, so don’t be alarmed when you aren’t seeing them.

Subsequent, add the next to the file:

[xdebug]
zend_extension="xdebug.so"
xdebug.mode=debug
xdebug.client_host=127.0.0.1
xdebug.client_port="<the port (9003 by default) to which Xdebug connects>"

There are some things to notice about this suite of code:

  • You might have already got an [xdebug] part, through which case you possibly can omit the primary designation.
  • The zend_extension entry might have you so as to add the complete path of xdebug.so to attach.
  • Whereas it would seem like a placeholder, the xdebug.client_port parameter is the way you’ll set it inside your code.

When you add these, save and shut the file, then check the PHP model from the command line (utilizing php --version):

The Big Sur blue, red, and purple gradient desktop background, showing a macOS Terminal window. It shows the
Testing for the present installations for PHP and Xdebug utilizing the macOS Terminal.

If in case you have a working model of Xdebug, it should present as one of many PHP extensions. You may also add phpinfo(); to a brand new file and check this within the browser.

That is nearly all you’ll want to do to have Xdebug work as your default debugger with PhpStorm. The ultimate step earlier than utilizing it’s putting in a browser helper extension.

Putting in a Browser Helper Extension

The ultimate key connection you’ll must make is between your browser and PhpStorm, completed by activating step debugging on the server. When you might do that from the command line utilizing particular GET or POST values, it’s extra simple to make use of an extension.

We advocate using the devoted Xdebug Helper extension. You possibly can set up it in your browser of selection:

If you wish to discover different extensions, the JetBrains website provides a number of extra choices for the preferred browsers.

When you’ve put in your chosen browser extension, you shouldn’t have to regulate any additional configuration settings. From right here, you possibly can start to make use of Xdebug with PhpStorm.

Utilizing Xdebug

Whereas we’ll use PhpStorm right here, you’ll see an analogous format and interface between completely different IDEs — although there will even be some apparent variations.

There are a number of ideas that mix to kind the entire debugging expertise:

  • Breakpoints: These are the factors the place Xdebug will cease to allow you to examine the output. You’re capable of set as many of those as you’d like.
  • Listening for connections: You possibly can toggle this on and off, although most builders will at all times go away it on.
  • The debugging display: The vast majority of your time will probably be spent inside the debugging interface — it’s the place you’ll work with the varied traces of code, variables, and parameters.

Step one is to activate listening — you received’t have the ability to debug something with out it. To do that, click on on the Run > Begin Listening for PHP Debug Connections choice within the toolbar:

A partial PhpStorm interface screen, showing a tree directory on the left, and the application toolbar. The Run menu is open, and the
The open Run menu inside PhpStorm.

As a substitute, you possibly can click on on the “phone” icon inside PhpStorm’s toolbar:

A close-up of the PhpStorm toolbar, which displays options for the current run configuration, various Git options, and the Start Listening for PHP Debug Connections telephone icon (complete with tooltip).
Listening for PHP debug connections utilizing the phone icon inside the PhpStorm toolbar.

Both of those choices will begin the listening for connections.

From right here, you possibly can start to set breakpoints inside the code editor’s gutters. A purple dot signifies a breakpoint, which you’ll click on to activate:

A close-up of the PhpStorm interface, showing a tree directory on the left, and the coding panel on the right. Within the gutters of the editor, there are red dots with white ticks at lines 45, 50, and 55. These are breakpoints for debugging.
Breakpoints inside the gutter of a PhpStorm enhancing web page.

If you need to debug your code, essentially the most simple means is to start listening, set breakpoints, then head to the precise web page in your browser. Find the icon on your extension inside the browser, then click on on it and choose the “Debug” choice:

The Mozilla Firefox browser, showing the green background (and
Choosing the Debug choice inside the browser toolbar utilizing a devoted extension.

This can open the debugger in PhpStorm and ship both the great or dangerous information:

A partial PhpStorm screen, showing an open debugger panel. The left shows various breakpoints, complete with filenames, line numbers, and function references. The right shows the values of the variables throughout the code, along with the value types.
Utilizing the PhpStorm debugger with Xdebug.

If you happen to right-click on the varied values, attributes, parameters, and variables, you’ll have the ability to entry an additional context menu. This provides you loads of additional scope to check and debug your code:

A portion of the PhpStorm Debugger interface with a list of breakpoints, filenames, line numbers, and function references on the left. The right shows a highlighted value within the code, with a context menu open. Among the options is
Utilizing the right-click context menu inside the PhpStorm Debugger to set new values.

For instance, you could possibly set completely different values for variables alongside the trail. This could be a deliberate try to interrupt your code and see what occurs, or it might be a strategy to check out code that already wants a repair. Both means, this provides you a unbelievable technique for debugging your code with out having to change it first.

How Kinsta Helps You to Debug Your WordPress Web site

WordPress comes with its personal set of debugging options by way of WP_DEBUG and different instruments, such as Query Monitor. These allow a mode through which you’ll begin to see beforehand hidden error messages throughout your web site and dashboard. From there, you possibly can start to determine what the issue is.

You may also save these error messages utilizing WP_DEBUG_LOG, which supplies you a strategy to doc the problems together with your web site. We cowl easy methods to set this up in another article on the blog. It is a breeze to arrange by way of your MyKinsta dashboard (and the Websites > Instruments display):

The MyKinsta dashboard, showing the left-hand purple sidebar, and a further gray submenu. There are two options to toggle here — a search and replace tool on the right, and the WordPress debugging tool on the left.
The WordPress debugging choice inside the MyKinsta dashboard.

If you happen to pair this with the free DevKinsta local environment tool, you’ll even have a one-click strategy to enable and disable WP_DEBUG for every web site you spin up:

The DevKinsta dashboard for a single site. It shows the database settings, including host, port, name, and user credentials. There is also a
Enabling WP_DEBUG inside DevKinsta’s management panel.

This implies you possibly can catch errors in your web site throughout growth, and ensure they don’t make it by way of to your stay web site. These modes are additionally straightforward to show off — very important for each site and user security.

All Kinsta plans additionally include the built-in Kinsta APM tool, which is our custom-designed efficiency monitoring device for WordPress websites.

Command Cheat Sheet

Earlier than we wrap up this publish, we must always point out shortcuts.

Like many different software program items, there are numerous methods to navigate round Xdebug (and PhpStorm) utilizing the keyboard alone. The truth is, you could possibly even use the command line to debug PHP scripts.

As soon as Xdebug is up and working, you should use the next instructions to get round:

Command Shortcut
Particular the port to pay attention on (resembling [9003]) -p [value]
Units a breakpoint on the desired line for the file path given. breakpoint_set -t line file:///<path> -n <line>
Runs your script till the tip, or the subsequent breakpoint run
Steps into the subsequent executable line step_into
Lists variables and values within the present scope context_get
Shows the worth of the desired property property_get -n <property>

Whereas your particular code editor could have its personal devoted shortcuts, the main target right here is on PhpStorm. Check out this desk of keyboard shortcuts for utilizing Xdebug with PhpStorm:

Command Home windows macOS
Discover Motion Ctrl + Shift + A Shift + Cmd + A
Open the Debugger Shift + F9 Ctrl + D
Toggle Breakpoint Management + F8 Cmd + F8
Step Into F7 F7
Step Over F8 F8
View Breakpoints Ctrl + Shift + F8 Shift + Cmd + F8
Resume the Program F9 F9
Consider the Present Expression Alt + F8 Possibility + F8

Fortunately, there isn’t quite a bit to memorize right here. You need to open the debugger, set breakpoints per line, pay attention for connections, and run your scripts.

Nonetheless, when you want a shortcut for a selected process, you should use the PhpStorm Discover Motion command:

The PhpStorm interface, showing the Find Action display. There are various search filters for All, Classes, Files, Symbols, Actions, and Git. The search term is
Utilizing the Discover Motion menu inside PhpStorm.

As soon as you start to sort on this area, you’ll be proven a dynamic listing of instructions and associated shortcuts. You may also discover a PDF model of all keyboard shortcuts by way of the Assist > Keyboard Shortcuts PDF menu.

If you would like extra of a real-time take a look at shortcuts as you’re employed with the mouse, JetBrains gives the Key Promoter X plugin:

A PhpStorm interface window, showing a number of options to find files and projects alongside the corresponding shortcuts. There are two notifications in the bottom right-hand corner with the format of
The PhpStorm interface displaying Key Promoter X notifications.

This helpful device will show notifications of your newest carried out motion, together with its associated keyboard shortcut. When you study and use the shortcuts, you possibly can part this plugin out and restore that helpful actual property to your display.

As any developer can attest, code is never ready for production after the first draft. Debugging is key- which is where Xdebug comes in 🐛Click to Tweet

Abstract

The apply of debugging has come a great distance from its humble beginnings; it now encompasses a a lot wider scope than its progenitors might have probably imagined. To hold out a radical job in the case of fixing your PHP code, you’ll want to make use of a reliable device. There are numerous excellent extensions and instruments to select from, however Xdebug is an debatable frontrunner.

As we’ve seen, Xdebug can adapt to even essentially the most eclectic of tastes in code editors, and it’s particularly nice when paired with PhpStorm. Nonetheless, no matter your setup, there’ll usually be a model of Xdebug to fit your wants. On the entire, it’s a strong, versatile, and intuitive device to make use of.

Do you assume Xdebug deserves its excessive reward, or is there one other debugging device that you simply want? Tell us within the feedback part under!


Save time, prices and maximize web site efficiency with:

  • On the spot assist from WordPress internet hosting consultants, 24/7.
  • Cloudflare Enterprise integration.
  • International viewers attain with 35 knowledge facilities worldwide.
  • Optimization with our built-in Software Efficiency Monitoring.

All of that and rather more, in a single plan with no long-term contracts, assisted migrations, and a 30-day-money-back-guarantee. Check out our plans or talk to sales to search out the plan that’s best for you.



offshore vps