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

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

Patricia Arquette
Release: 2024-11-29 03:33:14
Original
296 people have browsed it

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

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:

  1. Open the SSH Client: Open your preferred SSH client (e.g., PuTTY) and establish a connection to your remote Linux machine.
  2. Create the SSH Tunnel: Enter the following command to create a tunnel from your local workstation port (e.g., 3307) to the MySQL server's remote IP address and port (e.g., 10.3.1.55:3306):
ssh -fNg -L 3307:10.3.1.55:3306 username@ssh-jumpbox.com
Copy after login
  1. Configure the SSH Server: If necessary, configure the SSH server to allow local port forwarding by editing the /etc/ssh/sshd_config file and adding the following line:
AllowTcpForwarding yes
Copy after login
  1. Restart the SSH Server: Restart the SSH server to apply the changes:
sudo systemctl restart sshd
Copy after login

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

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!

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