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

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

Patricia Arquette
Release: 2024-11-29 00:52:11
Original
700 people have browsed it

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

Connecting to MySQL over SSH in PHP

Background: SSH Tunneling for Database Connectivity

Connecting to a remote database over SSH provides a secure and efficient means of data access. SSH serves as an encrypted channel through which your MySQL queries are transmitted, protecting sensitive information from interception.

SSH Tunnel Configuration

To establish the SSH tunnel, use the ssh command with the -L switch to specify local port forwarding. This switch redirects traffic from a specified local port to the database server's remote IP address and port over SSH.

For example, the following command sets up a tunnel from local port 3307 to the database server at 10.3.1.55:3306 through the SSH proxy at ssh-jumpbox.com:

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

MySQL Connection via Tunnel

Now that the tunnel is established, configure your PHP application to connect to the database through the local port. This involves specifying "127.0.0.1:3307" as the host parameter in your MySQL connection function, as seen in the example below:

$smysql = mysql_connect("127.0.0.1:3307", "dbuser", "passphrase");
Copy after login

This connection string points MySQL to use the local port 3307, which will be forwarded over the SSH tunnel to the database server.

Troubleshooting: Resolving Parameter Mismatch

The error "mysqli_connect() expects parameter 6 to be string, resource given" when using mysqli_connect indicates a mismatch in the function parameters. Ensure that the fifth parameter (which should be the tunnel resource) is a string containing the resource connection details, rather than the resource itself.

The above is the detailed content of How to Securely Connect to a 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template