How to Debug PHP Code on EC2 with PhpStorm and Xdebug

How to Debug PHP Code on EC2 with PhpStorm and Xdebug

Takahiro Iwasa
Takahiro Iwasa
2 min read
EC2 PHP PhpStorm

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:

SoftwareVersion
PHP7.1.7
Apache2.2.32-1.9
PhpStorm2017.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

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:

FieldValue
NameEC2 private IP
HostEC2 public IP
DebuggerXdebug
Use path mappingsON
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:

  1. Place a breakpoint at the desired position in your PHP code.
  2. Enable Listen for PHP Debug Connections mode in PhpStorm.
  3. 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! 🚀

Takahiro Iwasa

Takahiro Iwasa

Software Developer at KAKEHASHI Inc.
Involved in the requirements definition, design, and development of cloud-native applications using AWS. Now, building a new prescription data collection platform at KAKEHASHI Inc. Japan AWS Top Engineers 2020-2023.