How to Debug PHP Code on EC2 with PhpStorm and Xdebug
Introduction
Debugging PHP code running on remote EC2 instances can be challenging. However, with the right setup using PhpStorm and Xdebug, you can streamline your debugging process and improve development efficiency. This guide provides a comprehensive walkthrough of setting up your environment.
Prerequisites
Before starting, ensure the following software versions are installed:
Software | Version |
---|---|
PHP | 7.1.7 |
Apache | 2.2.32-1.9 |
PhpStorm | 2017.1.4 |
Server Configuration
Add the necessary Xdebug settings to the php.ini
file and restart the Apache server:
[xdebug]
zend_extension="/opt/remi/php71/root/usr/lib64/php/modules/xdebug.so"
xdebug.remote_enable = 1
xdebug.remote_connect_back = 1
xdebug.remote_host = "127.0.0.1"
xdebug.idekey = "IDE_KEY"
xdebug.remote_autostart=true
xdebug.so
may vary depending on your environment. Verify the correct path before applying these settings.
Restart Apache by running:
sudo service httpd restart
PhpStorm Configuration
Open Run > Edit Configurations...
in PhpStorm, then select PHP Remote Debug
.
Adding a Server
Click Servers
and add a target server with the following configuration:
Field | Value |
---|---|
Name | EC2 private IP |
Host | EC2 public IP |
Debugger | Xdebug |
Use path mappings | ON |
Absolute path | /var/www/html/<YOUR_WEB_APP_ROOT> |
Set the IDE key you defined in the xdebug.idekey
field of php.ini
.
Port Forwarding
If you are using a network router, configure port mapping to allow incoming connections to port 9000 and forward them to your localhost.
Debugging Your Code
To start debugging:
- Place a breakpoint at the desired position in your PHP code.
- Enable Listen for PHP Debug Connections mode in PhpStorm.
- Access your EC2 instance via a web browser.
When the breakpoint is triggered, PhpStorm will pause execution, allowing you to inspect and debug the code.
Conclusion
With this setup, you can efficiently debug PHP applications hosted on AWS EC2, leveraging the power of PhpStorm and Xdebug. This workflow ensures better visibility into code execution and simplifies debugging complex issues.
Happy Coding! 🚀