Debugging Web Applications In PHPStorm With Xdebug And Docker

From Littledamien Wiki
Jump to navigation Jump to search

Overview[edit]

How to debug a PHP web application in PHPStorm using Docker and XDebug. [1] [2]

PHPStorm configuration[edit]

PHP Interpreter[edit]

Make sure that a PHP interpreter is selected, and that the PHP installation has XDebug included.

In PHPStorm: Preferences > Language & Frameworks > PHP > CLI interpreter

From the command line: php -v. Make sure that the xdebug extension is displayed.

Docker server[edit]

The Docker server is a virtual Linux server that runs the web server which is used to host the web application to be debugged. It is important to keep in mind that the software and filesystem of this server is independent of the local filesystem where the app is being developed.

When this virtual server is spun up, it must be configured such that it can host the web application in a state where it can be run and debugged.

Preferences > PHP > Servers

Click the "plus" icon to create a new server.

  • Name: docker-server
  • Host: localhost
  • Port: 80
  • Debugger: Xdebug
  • Use path mappings: checked

Then under path mappings create associations between project files and their respective locations in the Docker container, e.g.:

  • /project_root/app/ > /var/www/html/
  • /project_root/keys/ > /var/www/keys/
  • /project_root/vendor/ > /var/www/html/vendor/

The host and port reference host and port within the Docker container. This applies to the path mappings as well.

The container's HTML root is /var/www/html. This path may or may not exist on the local file system, but that doesn't impact anything here.

Two project file directories cannot point to the same path on the server (e.g. bfhhand_web and common_lib can't coexist in the same root directory as they do on production.)

Run configuration[edit]

Run > Edit Configurations...

Click the "plus" icon to create a new Debug Configuration.

Select PHP Remote Debug

  • Name: docker
  • Server: docker-server
  • IDE key: PHPSTORM

docker-server is the server created in the previous step.

The value of the IDE Key must match the value that is put into the xdebug.ini file that is created later in the process and the IDE key that is used in the Xdebug Helper Chrome extension.

Error creating thumbnail: File missing

Xdebug preferences[edit]

These are the defaults, they can be confirmed, but don't need to be changed

Preferences > Languages & Frameworks > PHP > Debug > Xdebug

  • Debug port: 9003
  • Can accept external connections: checked

9003 is the default port for XDebug v3. 9000 is the default port for XDebug v2.

Validating the server in PHPStorm[edit]

Run menu > Web Server Debug Validation

  • Local Web Server or Shared Server: checked
  • Path to create validation script: [/local/path/to/web/app/]
  • URL to validation script: http://localhost
  • Click Validate

Docker container configuration[edit]

The three files used in the Docker container configuration (Dockerfile, xdebug.ini, docker-compose.yml) are all located in the PHPStorm project root directory. These files should not be uploaded to production. The actual web files should be placed one directory down from the root, e.g. in a directory named app.

Dockerfile[edit]

FROM php:7.4-apache

# install utilities such as curl, git, vim
RUN apt-get update &&\
    apt-get install --no-install-recommends --assume-yes --quiet ca-certificates curl git vim &&\
    rm -rf /var/lib/apt/lists/*

# install php extensions redis, xdebug, mysqli, etc.
RUN pecl install redis \
    && pecl install xdebug \
    && docker-php-ext-install mbstring pdo pdo_mysql mysqli \
    && docker-php-ext-enable redis xdebug

# create accessible apache logs
RUN mkdir /var/log/httpd/
ENV APACHE_LOG_DIR /var/log/httpd

# enable mod_rewrite
RUN a2enmod headers rewrite

# bypass CMS password in development environment
RUN mkdir /home/myacct/ && \
	mkdir /home/myacct/.htpasswds/ && \
	mkdir /home/myacct/.htpasswds/mysite/
COPY app/.htaccess /home/myacct/.htpasswds/mysite/

RUN mkdir /home/chicot/ && \
    mkdir /home/chicot/keys/ && \
    mkdir /home/chicot/keys/littledamien
COPY keys/littledamien/passwd /home/chicot/keys/littledamien/

# PHP and Xdebug settings
COPY container_files/xdebug.ini /usr/local/etc/php/conf.d/
COPY container_files/php.ini /usr/local/etc/php/

# make httpd accessible
EXPOSE "80"

The most important functions of this file are

  • Pull a PHP image.
  • Install Xdebug and MySql PHP extensions.
  • Copy local php.ini and xdebug.ini files containing necessary settings to the server.
  • Makes http port 80 available in the container.

Other conveniences built into the file:

  • Install curl, git, and vim in the container.
  • Log server errors to accessible log file.
  • Enable mod_rewrite directives and any non-default modules referenced in .htaccess.

See XDebug Dockerfile With PHP 5.x for a previous version of the Dockerfile.

php.ini[edit]

Place an php.ini file in the project filesystem (just not in with the web app files) and use Dockerfile to copy it to the Docker container.

Make sure that the php.ini file contains

error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
zend_extension=xdebug

The error_reporting setting doesn't impact xdebug's performance, but it does display important errors in the browser.

xdebug.ini[edit]

Place an xdebug.ini file in the project filesystem (just not in with the web app files) and use Dockerfile to copy it to the Docker container.

xdebug.mode=debug
xdebug.start_with_request=yes
xdebug.idekey="PHPSTORM"
xdebug.discover_client_host=0
xdebug.client_host=docker.for.mac.localhost
  • xdebug.mode=debug enabled xdebug
  • xdebug.start_with_request=yes allows the IDE to capture xdebug connections
  • xdebug.idekey is the key that matches the Xdebug Helper Chrome extension and the PHPStorm Debug configuration.
  • xdebug.discover_client_host and xdebug.client_host allow the Docker container to connect to the local machine.

docker-compose.yml[edit]

version: '2'
services:
  app:
    build:
      context: .
    image: xdebug-bfhhand:latest
    volumes:
      - ./:/var/www/html
      - ~/develop/bfhhand/keys:/var/www/keys
      - ~/develop/common_lib:/var/www/html/common_lib
    ports:
      - "80:80"
  • The context directive specifies where the Dockerfile is located.
  • image specifies the name of the Docker container that will be created.
  • volumes maps local directories to directories in the Docker container. These mappings correspond to the mappings found in PHPStorm > Preferences > Language & Frameworks > PHP > Servers > docker > path mappings.
  • ports maps the port used to reach the container with the port used inside the container.

Xdebug Helper Chrome Extension[edit]

Make sure the Xdebug Helper Chrome extension is installed in Chrome.

The icon (a little bug) for the extension should be displayed in Chrome's menu bar.

Click the icon and select Debug. PHPStorm will not be able to catch debug connections when the extension is disabled.

The IDE Key setting must match the value that is entered in PHPStorm's Debug preferences.

  • Chrome > Three dot pulldown menu (upper right) > More Tools > Extensions
  • Xdebug Helper > Details button
  • Extension Options > IDE Key
    • Select 'PHPStorm' from the dropdown options on the left.
    • Enter the IDE key value on the right.

Managing the Docker server[edit]

Start the Docker server[edit]

$ docker-compose build
$ docker-compose up -d
$ curl localhost

or simply

$ docker-compose up -d --build
$ curl localhost

The -d option is for "detached" to get the terminal prompt back after running the command.

The server is tested with curl localhost.

Stop the Docker server[edit]

$ docker-compose down

Remove the image with

$ docker rmi [IMAGE_NAME]

Connecting the the Docker container with PHPStorm[edit]

Chrome extension[edit]

The browser extension is not necessary if XDebug is configured with xdebug.start_with_request=1.

Install XDebug Helper extension in browser.

In the extension options, select PHPStorm as the predefined IDE key (PHPSTORM) or "Other" to specify a custom IDE key. This key must match the key specified in the docker run configuration (Run menu > Edit Configurations... > IDE Key (Session ID)), and it must match the xdebug.idekey value in xdebug.ini.

Make sure that the extension is active by clicking on the extension icon in the browser toolbar, and selecting "Debug". The icon is gray when disabled and green when enabled.

PHPStorm[edit]

Error creating thumbnail: File missing

After creating the "docker" run configuration in PHPStorm (see above), "docker" will be one of the options available in the run configuration drop-down in the top toolbar.

Select docker in that dropdown to make it the active run configuration, however it's not necessary to start a debugging session.

Select Run > Start Listening for PHP Debug Connections to have PHPStorm listen for connections to the docker server, i.e. requests for "localhost" in a browser.

Request site content[edit]

Then in a browser make a request for http://localhost, or in a terminal window enter curl localhost. The IDE will automatically catch the request and break at any breakpoints.

Select Run > Break at first line in PHP scripts to catch all requests to the docker server, or place a breakpoint in the page of interest.

Uploading edits[edit]

Any changes to the source files in PHPStorm are immediately available on the server. The volumes directive in docker-compose.yml creates the links between the local source directories and the server directories.

Database connections[edit]

Assuming the development database server is running on the same machine as PHPStorm. "localhost" to the Docker web server is the Docker container, and not the development machine. Use host.docker.internal as the host setting for database connections. This will resolve as the development machine for the web server.

Database connections[edit]

Development environment considerations[edit]

There is a single development MariaDB server. Local development machines are not hosting database servers themselves.

The Docker container can only connect to two machines for the purpose of database connections, either itself or the machine hosting the Docker container.

Creating a database on the Docker container each time it is created is too unwieldy considering the data has to be imported into the database also.

Hosting the database on the local machine runs the risk of getting out of sync with other development machines.

Configuration[edit]

The Docker container makes a database connection to the machine hosting the container. This connection is forwarded by the local machine to a remote machine hosting a MariaDB server via SSH Tunneling.

The local machine listens for MySQL connections on a non-standard port and forwards that port to the remote host.

The database connection settings for the Docker container are:

  • host: host.docker.internal - This translates to the machine hosting the Docker container.
  • port: 8888 - An arbitrary non-standard MySQL/MariaDB port.

The local machine must establish an SSH Tunnel:

$ ssh -fN -L 8888:[REMOTE_SERVER]:3307 -p [NONSTANDARD_SSH_PORT] [USER]@[REMOTE_SERVER]

Troubleshooting[edit]

PHP[edit]

In a PHP page on the server call phpinfo(). Navigate to the page in a browser and it will display all the PHP settings loaded from php.ini and the location of the php.ini file that was loaded.

Xdebug[edit]

In a PHP page on the server call xdebug_info(). Navigate to the page in a browser and it will display the current xdebug settings along with the location of the files (php.ini and xdebug.ini) used to load the settings.

Validating the server in PhpStorm[edit]

Action

  1. Test the debug environment with PhpStorm main menu > Run > Web Server Debug Validation.
    1. Local Web Server or Shared Folder: selected
    2. Path to create validation script: [/path/to/project_root]/app
    3. URL to validation script: http://localhost
  2. Click Validate button

Expected result

All validation marked with green check marks.

Erroneous result

PhpStorm can't connect to the web server due to 401 error.

Fix

Confirm that connections to the local development server don't invoke Apache password protection.

AuthType Basic
AuthName "Authorization required"
AuthUserFile "/path/to/auth_dir/passwd"
<RequireAny>
	Require ip 172.19.0
	Require valid-user
</RequireAny>

The IP comes from the Docker container and can be discovered with

$ docker inspect [DOCKER_CONTAINER_NAME] | grep 'IPAddress'

See also[edit]

External links[edit]

Notes[edit]