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

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

DDD
Release: 2024-11-24 06:33:13
Original
537 people have browsed it

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

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>
Copy after login

Replace with the port you want to use on your local machine (e.g., 3307), with the IP address of your database server, with the port number of your database, with your SSH username, and with the SSH proxy host's address.

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
Copy after login

Replace with the port you specified in Step 1, with your database username, and enter your password when prompted.

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); 
?>
Copy after login

Replace with the port you specified in Step 1, with your database username, and with your database password.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template