Mark Jaquith

Quickly Toggle Xdebug on macOS

September 20, 2020

Xdebug is an invaluable tool when doing hardcore PHP debugging. But it is super slow. Like, 100-300% slower than PHP without it.

I only sometimes need Xdebug. I’m fine using var_dump() or whatever for quick inspection. But I’d also like to quickly enable Xdebug when needed.

Here’s what I added to my zsh setup to do that (should work the same in Bash):

# Comment out ini files.
alias ini-disable="sed -iE 's/^;* */; /'"
alias ini-enable="sed -iE 's/^;* *//'"

# Toggle Xdebug.
function xdebug-on() {
	ini-enable $(php -i | grep xdebug.ini)
	brew services restart php
}

function xdebug-off() {
	ini-disable $(php -i | grep xdebug.ini)
	brew services restart php
}

Now I can just run xdebug-on and xdebug-off to toggle it, in a few seconds. I also set up a 2am cron job to turn it off, in case I forget.

0 2 * * * source ~/.zshrc && xdebug-off >/dev/null 2>&1

This assumes a few things:

  1. You have PHP installed via Homebrew. May God have mercy on your soul if you’re developing in Docker.
  2. Xdebug is installed. pecl install xdebug did it for me.
  3. All of your Xdebug configuration, including the line that enables xdebug.so lives inside a config file called xdebug.ini. A good place for this is your PHP install’s conf.d directory. The command looks for it in your PHP config, so it doesn’t matter where it’s located — just that it is named xdebug.ini. Note that by default PECL will stick your zend_extension="xdebug.so" line at the top of your php.ini file, so you will want to move that and all your other Xdebug configuration into conf.d/xdebug.ini.