Editing
Debugging Web Applications In PHPStorm With Xdebug And Docker
Jump to navigation
Jump to search
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== Overview == How to debug a PHP web application in PHPStorm using Docker and XDebug. <ref>[https://serversforhackers.com/c/getting-xdebug-working Getting xDebug to Work] - Servers For Hackers</ref> <ref>[https://gist.github.com/chadrien/c90927ec2d160ffea9c4 Debug your PHP in Docker with Intellij/PHPStorm and Xdebug] - GitHub Gist</ref> == PHPStorm configuration == === PHP Interpreter === Make sure that a PHP interpreter is selected, and that [[Debugging_PHP|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 === 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/` [[File:phpstorm-preferences-php-server.png|1024px]] 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 === '''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 [[File:Php-docker-run-configuration.png]] `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. [[file:Phpstorm-php-debug-pref.png|474px|right]] === Xdebug preferences === 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 === '''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 == 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 === <syntaxhighlight lang="docker"> 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" </syntaxhighlight> 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 === 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 <pre> error_reporting = E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT zend_extension=xdebug </pre> The `error_reporting` setting doesn't impact xdebug's performance, but it does display important errors in the browser. === xdebug.ini === 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. <pre> xdebug.mode=debug xdebug.start_with_request=yes xdebug.idekey="PHPSTORM" xdebug.discover_client_host=0 xdebug.client_host=docker.for.mac.localhost </pre> * `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 === <syntaxhighlight lang="yaml"> 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" </syntaxhighlight> * 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 == 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 == === Start the Docker server === <syntaxhighlight lang="bash"> $ docker-compose build $ docker-compose up -d $ curl localhost </syntaxhighlight> or simply <syntaxhighlight lang="bash"> $ docker-compose up -d --build $ curl localhost </syntaxhighlight> 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 === <syntaxhighlight lang="bash"> $ docker-compose down </syntaxhighlight> Remove the image with <syntaxhighlight lang="bash"> $ docker rmi [IMAGE_NAME] </syntaxhighlight> == Connecting the the Docker container with PHPStorm == === Chrome extension === <div class="alert alert-info">The browser extension is not necessary if XDebug is configured with `xdebug.start_with_request=1`.</div> Install [https://confluence.jetbrains.com/display/PhpStorm/Browser+Debugging+Extensions 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 === [[file:Phpstorm-docker-run-configuration.png|410px|right]]After creating the "docker" run configuration in PHPStorm ([[#Run_configuration|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 === 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 === 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 === 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 == === Development environment considerations === 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 === 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_Tunnel|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]]: <pre> $ ssh -fN -L 8888:[REMOTE_SERVER]:3307 -p [NONSTANDARD_SSH_PORT] [USER]@[REMOTE_SERVER] </pre> == Troubleshooting == === PHP === 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 === 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 === '''Action''' # Test the debug environment with '''PhpStorm''' main menu > '''Run''' > '''Web Server Debug Validation'''. ## '''Local Web Server or Shared Folder''': selected ## '''Path to create validation script''': `[/path/to/project_root]/app` ## '''URL to validation script''': `http://localhost` # 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. <syntaxhighlight lang="apache"> AuthType Basic AuthName "Authorization required" AuthUserFile "/path/to/auth_dir/passwd" <RequireAny> Require ip 172.19.0 Require valid-user </RequireAny> </syntaxhighlight> The IP comes from the Docker container and can be discovered with <syntaxhighlight lang="bash"> $ docker inspect [DOCKER_CONTAINER_NAME] | grep 'IPAddress' </syntaxhighlight> == See also == === External links === * [https://www.jetbrains.com/help/phpstorm/2021.1/zero-configuration-debugging.html Zero-Configuration Debugging] -- PHPStorm Documentation * [[Docker Cookbook]] * [https://xdebug.org/docs/remote Xdebug Extension for PHP documentation] === Notes === <references /> [[Category:BFH Handwriting]] [[Category:PHP]] [[Category:Web Development]]
Summary:
Please note that all contributions to Littledamien Wiki may be edited, altered, or removed by other contributors. If you do not want your writing to be edited mercilessly, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource (see
Littledamien Wiki:Copyrights
for details).
Do not submit copyrighted work without permission!
Cancel
Editing help
(opens in new window)
Navigation menu
Personal tools
Not logged in
Talk
Contributions
Create account
Log in
Namespaces
Page
Discussion
English
Views
Read
Edit
View history
More
Search
Navigation
Main page
Recent changes
Random page
Help about MediaWiki
Tools
What links here
Related changes
Special pages
Page information