Home >Database >Mysql Tutorial >How Can I Securely Connect to a Remote MySQL Database via SSH Using PHP?

How Can I Securely Connect to a Remote MySQL Database via SSH Using PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 12:00:18502browse

How Can I Securely Connect to a Remote MySQL Database via SSH Using PHP?

MySQL Remote Connection over SSH Using PHP

To establish a secure connection to a remote MySQL database over SSH, consider employing the following approaches:

SSH Tunnel Method

  • Step 1: Set up SSH Tunnel

Utilize the command line to establish an SSH tunnel like this:

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

where:

  • 3307: Local port on your machine
  • 10.3.1.55: MySQL database server address
  • 3306: MySQL database port
  • Step 2: Connect via SSH Tunnel

Instruct your MySQL client to connect through the tunnel:

mysql -h 127.0.0.1 -P 3307 -u dbuser -p passphrase
  • Step 3: PHP Connection

Connect your PHP application to the tunnel:

$smysql = mysql_connect("127.0.0.1:3307", "dbuser", "passphrase");
mysql_select_db("db", $smysql);

Security Considerations

It's crucial to prioritize security when establishing remote MySQL connections. Ensure the Jumpbox/Bastion Host is the tunnel target and not the database server. This mitigates the risk of exposing your database to the internet. Consider utilizing SSH key authentication for enhanced security.

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

Statement:
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