PHP MySQL remote connection timeouts occur when your PHP script cannot establish or maintain a connection to a MySQL database over a network. This usually happens due to network restrictions, incorrect server settings, or firewall rules—not a problem with PHP itself. The fix involves verifying connectivity, adjusting MySQL and server configurations, and ensuring proper authentication. You’ll need access to both the web server (running PHP) and the database server (running MySQL), plus administrative privileges on the database server.

What You'll Need

  • SSH access or direct console access to the MySQL server
  • PHP installed on the web server (with mysqli or PDO MySQL extension enabled)
  • MySQL root or administrative credentials on the database server
  • Network access details: IP addresses, ports (default 3306), and firewall rules
  • Time and patience—remote MySQL debugging often requires multiple systems checks

Step-by-Step

  1. Verify basic network connectivity to the MySQL port
    On the PHP/web server, run: telnet [mysql-server-ip] 3306 (or nc -zv [mysql-server-ip] 3306 on Linux/macOS). If the connection hangs or times out, the issue is network- or firewall-related—not PHP. If telnet isn’t installed, try curl -v telnet://[mysql-server-ip]:3306 or use PowerShell’s Test-NetConnection [mysql-server-ip] -Port 3306 on Windows.
  2. Check if MySQL is listening on the correct interface
    On the MySQL server, open /etc/mysql/mysql.conf.d/mysqld.cnf (or /etc/my.cnf) and locate the bind-address directive. If it says 127.0.0.1, MySQL only accepts local connections. Change it to 0.0.0.0 (to listen on all interfaces) or the server’s public/private IP (e.g., 192.168.1.100). Save the file, then restart MySQL: sudo systemctl restart mysql or sudo service mysql restart.
  3. Confirm user permissions for remote access
    Log into MySQL locally on the database server: mysql -u root -p. Run:
    SELECT host, user FROM mysql.user WHERE user = 'your_php_user';
    If the host column shows only localhost, the user can’t connect remotely. Create a new user or update permissions:
    CREATE USER 'your_php_user'@'%' IDENTIFIED BY 'strong_password';
    GRANT ALL PRIVILEGES ON your_database.* TO 'your_php_user'@'%';
    FLUSH PRIVILEGES;
    Using '%' allows connections from any host—restrict it to a specific IP (e.g., 'your_web_server_ip') for better security.
  4. Open the MySQL port in the firewall
    On the MySQL server, check active firewall rules: sudo ufw status (Ubuntu) or sudo firewall-cmd --list-all (CentOS/RHEL). If port 3306 is blocked, allow it:
    sudo ufw allow 3306/tcp
    or, for CentOS/RHEL:
    sudo firewall-cmd --permanent --add-port=3306/tcp && sudo firewall-cmd --reload
    Cloud providers (AWS, GCP, Azure) require additional steps: in the security group or network ACL, add an inbound rule for TCP port 3306, source = your web server’s IP (or private subnet).
  5. Adjust MySQL timeout settings
    Still experiencing timeouts after connection? Increase MySQL’s wait and timeout values. In mysqld.cnf, add or modify under the [mysqld] section:
    wait_timeout = 28800
    interactive_timeout = 28800
    net_read_timeout = 60
    net_write_timeout = 60
    Then restart MySQL. These defaults are often too low for long-running scripts or high-latency networks.
  6. Update your PHP connection code with proper timeouts
    In PHP, explicitly set connection and query timeouts. For mysqli:
    $mysqli = new mysqli();
    $mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
    $mysqli->real_connect('mysql-server-ip', 'user', 'pass', 'db');
    For PDO:
    $pdo = new PDO('mysql:host=mysql-server-ip;dbname=db', 'user', 'pass', [
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4',
    PDO::ATTR_TIMEOUT => 10
    ]);
    Without these, PHP uses system defaults (often 60+ seconds), masking network issues.
  7. Test with a minimal PHP script
    Create a simple test-mysql.php on your web server:
    <?php
    $link = mysqli_connect('mysql-server-ip', 'user', 'pass', 'db', 3306, 10);
    if (!$link) {
    die('Connection failed: ' . mysqli_connect_error());
    }
    echo 'Connected successfully';
    ?>
    Run it via CLI (php test-mysql.php) and via browser. CLI bypasses web server timeouts—discrepancies point to Apache/Nginx or PHP-FPM limits.

Common Mistakes

  • Assuming localhost works remotely—MySQL treats localhost (socket) and 127.0.0.1 (TCP) differently. Always use the IP in PHP config for remote connections.
  • Ignoring cloud provider defaults: AWS RDS and similar services block remote access by default unless the security group explicitly allows it.
  • Using bind-address = 0.0.0.0 without a firewall—this exposes the port to the internet, creating a security risk. Restrict access to known IPs instead.
  • Forgetting to restart MySQL after config changes—changes to mysqld.cnf don’t apply until the service reloads.
  • Overlooking PHP’s default_socket_timeout in php.ini—set it to at least 60 if your network is slow.

Tips

  • Use mysql -h [ip] -u user -p from the web server to test MySQL CLI connectivity before involving PHP.
  • Check MySQL error logs (/var/log/mysql/error.log) for denied connections or socket issues—this often reveals the root cause faster.
  • For production, avoid GRANT ... @'%'; use specific IPs or subnet ranges (e.g., 'web_user'@'192.168.1.%').
  • Enable MySQL slow query log to identify if timeouts stem from slow queries, not connectivity.
  • Consider SSH tunneling for debugging: ssh -L 3307:localhost:3306 user@mysql-server, then connect PHP to localhost:3307 to bypass network issues.
  • Set up monitoring (e.g., with netstat -tuln | grep :3306) to confirm MySQL listens on the expected interface after reboots.

Troubleshooting

If timeouts persist after following the steps above, investigate these less obvious causes:

  • SELinux blocking connections (common on CentOS/RHEL): Run sudo setsebool -P httpd_can_network_connect_db 1 to allow Apache/Nginx to reach remote databases.
  • Database server overload: High CPU or I/O wait may cause slow responses. Check with top, vmstat 1, or mysqladmin processlist.
  • NAT or routing issues: If servers are in different subnets or clouds, verify routing tables and NAT gateways allow bidirectional traffic.
  • PHP-FPM timeout limits: In /etc/php/[version]/fpm/php-fpm.conf, ensure request_terminate_timeout is ≥ your MySQL timeout. A lower PHP-FPM timeout kills the connection before MySQL responds.
  • SSL/TLS mismatches: If MySQL requires SSL but PHP doesn’t use it (or vice versa), connections may hang. Test with mysql --ssl-mode=DISABLED -h [ip] .... If it works, adjust PHP’s PDO/MySQLi to use SSL or relax MySQL’s SSL requirements.

Still stuck? Capture network traffic with tcpdump -i any port 3306 on the MySQL server while running your PHP script. If you see SYN packets but no SYN-ACK, the issue is network-layer. If SYN-ACK arrives but no data follows, check MySQL’s thread stack or buffer sizes.

Frequently Asked Questions

Why does my PHP connection work locally but not remotely?

MySQL’s user permissions and bind-address are likely restricted to localhost. Remote connections require explicit remote user grants and server-level network configuration.

Can I use a Unix socket for remote connections?

No. Unix sockets only work on the same machine. Remote connections must use TCP/IP, so always specify a host (IP or hostname) in PHP, not a socket path.

Is it safe to set bind-address to 0.0.0.0?

Only if you pair it with strict firewall rules (e.g., allow only your web server’s IP). Otherwise, it exposes MySQL to the internet, inviting brute-force attacks. Prefer binding to a private IP in the same VPC or subnet.

My timeout is still 30 seconds despite setting PHP’s timeout to 10. Why?

MySQL’s wait_timeout and interactive_timeout may be overriding your PHP settings. Ensure both client (PHP) and server (MySQL) timeouts are aligned.

How do I test if a cloud provider’s security group is blocking the connection?

From the web server, run telnet [rds-endpoint] 3306. If it hangs, check the database’s security group: inbound rules must allow your web server’s IP (or security group) on port 3306.

Can I use a VPN instead of opening MySQL to the public?

Yes. Setting up a site-to-site or client VPN (e.g., WireGuard) between servers lets MySQL keep bind-address = 127.0.0.1 while allowing secure remote access through the encrypted tunnel.