Vagrant remote PHP & CLI debugging with PHPStorm

First we will cover how to enable PHP remote debugging in PHPStorm if Vagrant is used and because this is so easy we also write a short Shell script to use remote PHP CLI debugging e. g. for Cronjob scripts or unit tests.

If you don't have a Vagrant box you can use my vagrant-librarian-puppet example. If you use this Vagrant box you can skip "Enable Xdebug PHP extension" and the URL is http://localhost:8080/.

Enable Xdebug PHP extension

To enable debugging you must configure Xdebug. Make sure you have installed the PHP Xdebug extension (sudo apt-get install php5-xdebug). Open your /etc/php5/conf.d/20-xdebug.ini (path depends on OS) and add the following lines:

xdebug.default_enable=1  
xdebug.remote_enable=1  
xdebug.remote_handler=dbgp  
xdebug.remote_host=10.0.2.2  
xdebug.remote_port=9000  
xdebug.remote_autostart=0  
xdebug.remote_connect_back=1  

The important point is xdebug.remote_host which can change on other system configurations, but it should work for the most common use cases. This IP address is the gateway of the vagrant box.

Remote PHP debugging

To start debugging you must set a cookie because autostart debugging is not enabled. There is a great Firefox add-on "The easiest Xdebug". If the cookie is set and you have enabled listening for incoming debug connections in PHPStorm a popup window should appear to configure your PHP servers. To avoid upcoming popups open the settings File -> Settings -> Languages & Frameworks -> PHP -> Server and remove the path of the file and set only the project root path. Don't forget to set a breakpoint in your PHP file.
Vagrant xDebug settings

Remote PHP CLI debugging

A Shell script is necessary for remote CLI debugging. Please create a file in your vagrant box with name cli_debug.sh and put the following lines in this file.

#!/bin/bash
export XDEBUG_CONFIG="idekey=PHPSTORM" &&  
export PHP_IDE_CONFIG="serverName=application" &&  
php "$@"  

To enable debugging you must specify the idekey and the serverName. PHPStorm uses the serverName to determine the right server. Copy the previous server config and rename it to application.
Vagrant xDebug settings cli Make this file executable with chmod +x cli_debug.sh and now you can start debugging of PHP CLI scripts with ./cli_debug.sh [Path to your PHP file]. If you use the vagrant-librarian-puppet example you can test it with ./cli_debug.sh /vagrant/public/index.php. Don't forget to set a breakpoint in your PHP file.

Vagrant SSH connection timeouts

On Windows 7 I have sometimes SSH connection timeouts. To solve this problem cancel the Vagrant up process (Strg + C) and execute vagrant reload or stop the box in VirtualBox and start it again with vagrant up, then it works. I don't know why this happens.

Resources

Article picture: code bug by gui.tavares under CC BY-NC 2.0

Discuss (0 Comments)