A bash script to run php commands with XDebug enabled.

I’m a big fan of XDebug. But it really slows down the PHP native tools I frequently use: Composer, Symfony console commands, phpunit, etc. So, I don’t leave it installed all the time on my development system. Instead I use this bash script to enable XDebug just when I want to debug:

#!/bin/bash
(
    PHP=${PHP:-/usr/bin/php}
    XDEBUG_SO=${XDEBUG_SO:-/usr/lib64/php/modules/xdebug.so}
    IDE_KEY=${IDE_KEY:-PHPSTORM}
    XDEBUG_HOST=${XDEBUG_HOST:-1.2.3.1}
    XDEBUG_PORT=${XDEBUG_PORT:-9001}

    nc -z ${XDEBUG_HOST} ${XDEBUG_PORT}

    if [ "$?" -ne 0 ]
    then
    echo "No listener at ${XDEBUG_HOST} ${XDEBUG_PORT}"
        exit
    fi

    export XDEBUG_CONFIG="idekey=${IDE_KEY} remote_host=${XDEBUG_HOST} remote_port=${XDEBUG_PORT}"

    ${PHP} \
        -didekey=${IDE_KEY} \
        -dzend_extension=${XDEBUG_SO} \
        -dxdebug.remote_enable=1 \
        -dxdebug.remote_mode=req \
        -dxdebug.remote_port=${XDEBUG_PORT} \
        -dxdebug.remote_host=${XDEBUG_HOST} \
          "$@"
)

For example:

xdebug yabot.php

The script also uses netcat (nc) to check that I have something listening at XDEBUG_HOST:XDEBUG_PORT and warns if I haven’t started my debug client (e.g. phpstorm) listening for connections.

There is one case where this approach doesn’t work: when php is being run by a web server (e.g. httpd or php-fpm).

My earlier blog post Laravel, Valet, and XDebug shows a quick work around for that case..

Comments are closed.