Securely Connecting to a MySQL Server Over SSH Using PHP
Connecting to a remote MySQL server over SSH provides additional security by encrypting the connection. In PHP, the mysqli_connect() function enables connection to SSH-tunneled MySQL servers. However, when attempting to establish a connection using ssh2_tunnel(), developers often encounter the error "mysqli_connect() expects parameter 6 to be string, resource given."
SSH Tunnel Configuration
The recommended approach to resolve this issue is to set up an SSH tunnel. Follow these steps to create an SSH tunnel using command line tools:
ssh -fNg -L 3307:10.3.1.55:3306 username@ssh-jumpbox.com
AllowTcpForwarding yes
sudo systemctl restart sshd
PHP Connection
Once the SSH tunnel is established, you can connect to the MySQL server using PHP:
$mysqli = new mysqli('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD', 'dbname', 3307); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); }
This code connects to the MySQL database hosted at 127.0.0.1:3307, using the specified database username, password, database name, and the port number configured for the SSH tunnel.
The above is the detailed content of How to Securely Connect to a Remote MySQL Server via SSH Tunnel in PHP?. For more information, please follow other related articles on the PHP Chinese website!