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.
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]
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");
This connection string points MySQL to use the local port 3307, which will be forwarded over the SSH tunnel to the database server.
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!