Home >Backend Development >PHP Tutorial >How to Securely Connect to a Remote MySQL Server Over SSH in PHP?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 22:33:30605browse

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

Securely Connect to a Remote MySQL Server over SSH in PHP

To establish a secure tunnel for PHP database connectivity, the following SSH tunnel solution offers a robust approach.

SSH Tunnel Setup

  1. Create an SSH tunnel to your MySQL database server. For this, use a command like:
ssh -fNg -L 3307:10.3.1.55:3306 [email protected] 
  1. Choose a local port (e.g., 3307) and forward all traffic to the remote database server's IP and port (10.3.1.55:3306).

PHP Connection

Once the SSH tunnel is established, you can connect to the database securely through PHP using:

<code class="php">$smysql = mysql_connect( "127.0.0.1:3307", "dbuser", "passphrase" );
mysql_select_db( "db", $smysql ); </code>

This will establish a connection to the remote database via the encrypted SSH tunnel.

Benefits

  • Encrypted Communication: Data is transmitted over an encrypted SSH connection, ensuring confidentiality.
  • Security Enhancement: Limiting direct access to the database server reduces security vulnerabilities.
  • Compatibility: Can be used with various PHP database functions, such as mysql_connect and mysqli_connect.

The above is the detailed content of How to Securely Connect to a Remote MySQL Server Over SSH in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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