Connect to a MySQL Server Over SSH in PHP
To establish a secure connection to your remote MySQL database using SSH and PHP, several approaches exist. One widely adopted method is setting up an SSH tunnel.
SSH Tunnel Solution
Step 1: Create an SSH Tunnel
Utilize a GUI MySQL client with SSH tunneling capabilities (e.g., Visual Studio Code, TablePlus) or the command line. If using the command line, execute the following command, substituting the necessary values:
ssh -fNg -L <local_port>:<database_server_addr>:<database_server_port> <username>@<ssh_proxy_host>
Replace
Step 2: Configure Your MySQL Client
Instruct your local MySQL client to connect through your SSH tunnel. For example, use the following command:
mysql -h 127.0.0.1 -P <local_port> -u <dbuser> -p
Replace
Step 3: Connect Using PHP
To connect to your MySQL database using PHP, utilize the following code:
<?php $smysql = mysql_connect("127.0.0.1:<local_port>", "<dbuser>", "<passphrase>"); mysql_select_db("db", $smysql); ?>
Replace
By following these steps, you can securely connect to your remote MySQL database over SSH and perform database operations using PHP.
The above is the detailed content of How Can I Securely Connect to a Remote MySQL Database via SSH Tunnel in PHP?. For more information, please follow other related articles on the PHP Chinese website!