You want to debug the code running inside your virtual machine, because being able to use a real debugger is better than echoing everything out.


You need to install the xdebug php module and configure it so it connects to the IDE on your host computer. After that, you will be able to halt the code execution, check variables live and step through your code looking for bugs.


Step 1: Install xdebug

First, you need to connect via SSH into your vagrant box to make changes to the system. Open your console, navigate to the project folder and type

vagrant ssh

After a few seconds, you will be logged into your vagrant box and perform commands.

Now we need to tell the system to install the xdebug module. Sadly there is no direct install method available through apt-get, so we need to install "pear" first (thats a php module system).

Run the following commands:

sudo apt-get install -y php-pear php-dev
sudo apt-get install -y gcc make autoconf libc-dev pkg-config php-pear

Now pear and pecl is available on your system and you can actually install xdebug:

sudo pecl install xdebug

Step 2: Configure xdebug

We need to update the php.ini to enable and configure xdebug. If you are using the most recent version 7.1 of PHP, the following commands apply:

sudo bash -c "echo >> /etc/php/7.1/apache2/php.ini"
sudo bash -c "echo xdebug.remote_enable = on >> /etc/php/7.1/apache2/php.ini"
sudo bash -c "echo xdebug.remote_connect_back = on >> /etc/php/7.1/apache2/php.ini"
sudo bash -c "echo xdebug.idekey = \"vagrant\" >> /etc/php/7.1/apache2/php.ini"

This adds 4 new lines of configuraton directly at the end of the php.ini file inside the php 7.1 folder. Change the filename according to your used php version.

And thats it! Whenever your browser sends a cookie with its request, xdebug will be enabled and tries to connect back to the computer that made the request. If your IDE is running there and waiting for an xdebug connection, you can start debugging.

I recomment using a xdebug plugin for chrome to enable/disable the debugger.