Home > Database > Mysql Tutorial > How to Securely Connect to a Remote MySQL Database via SSH Tunneling in PHP?

How to Securely Connect to a Remote MySQL Database via SSH Tunneling in PHP?

Barbara Streisand
Release: 2024-11-27 11:37:10
Original
288 people have browsed it

How to Securely Connect to a Remote MySQL Database via SSH Tunneling in PHP?

Establishing Secure Remote MySQL Connections via SSH in PHP

In this scenario, we encounter a challenge in establishing a connection to a remote MySQL database using SSH and PHP. The 'can't access' error persists despite granting the necessary permissions.

Addressing the Issue

To resolve this issue, we employ an SSH tunneling approach. This involves creating a secure connection to the database server through an SSH proxy, usually a Jumpbox server. This setup provides an encrypted channel for data exchange, mitigating security risks associated with direct database server exposure.

SSH Tunnel Configuration

  1. GUI Tools: Consider using graphical user interface (GUI) tools like Visual Studio Code or TablePlus that offer built-in SSH tunneling support. They simplify the process and enhance user experience.
  2. Command Line:

    a. Establish a local port forwarding tunnel on your workstation using the '-L' switch:

    ssh -fNg -L 3307:10.3.1.55:3306 [email protected] 
    Copy after login

    Where:

    • 3307: Local port for accepting connections
    • 10.3.1.55: Remote MySQL database server's IP address
    • 3306: MySQL database server's port

    b. Connect to the database server via the local port:

    mysql -h 127.0.0.1 -P 3307 -u dbuser -p passphrase
    Copy after login

    Where:

    • 127.0.0.1: Localhost (your workstation)
    • 3307: Local port established in step a
  3. PHP Connection:

    Once the tunnel is established, connect to the MySQL database using PHP as follows:

    <?php
       $smysql = mysql_connect("127.0.0.1:3307", "dbuser", "passphrase");
       mysql_select_db("db", $smysql);
    ?>
    Copy after login

Additional Considerations

  • Forward traffic to an internal address on your remote network to enhance security.
  • Utilize a private key for authentication instead of passwords.

The above is the detailed content of How to Securely Connect to a Remote MySQL Database via SSH Tunneling in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template