PHP 使用 SSH 连接 MySQL 数据库并不是一个常见的做法,因为通常情况下,PHP 应用程序直接通过 MySQLi 或 PDO 扩展与 MySQL 服务器通信。但是,如果你出于安全考虑需要通过 SSH 隧道来连接 MySQL,可以使用以下方法:
SSH(Secure Shell)是一种加密的网络协议,用于在不安全的网络上安全地运行网络服务。通过 SSH 隧道,你可以将本地端口转发到远程服务器上的 MySQL 端口,从而安全地访问数据库。
以下是一个使用 PHP 和 SSH 隧道连接 MySQL 数据库的示例:
ssh2
扩展创建 SSH 隧道首先,确保你的 PHP 安装了 ssh2
扩展。
<?php
$servername = "your_mysql_server";
$username = "your_mysql_username";
$password = "your_mysql_password";
$dbname = "your_database_name";
// SSH 连接参数
$ssh_host = "your_ssh_server";
$ssh_port = 22;
$ssh_username = "your_ssh_username";
$ssh_password = "your_ssh_password";
// 创建 SSH 连接
$connection = ssh2_connect($ssh_host, $ssh_port);
if (!$connection) {
die('Failed to connect to the SSH server');
}
// 验证 SSH 登录
if (!ssh2_auth_password($connection, $ssh_username, $ssh_password)) {
die('Failed to authenticate with the SSH server');
}
// 创建本地端口转发
$localPort = 3307; // 本地端口
$remotePort = 3306; // MySQL 服务器端口
$remoteHost = $servername; // MySQL 服务器地址
$socket = ssh2_tunnel($connection, $remoteHost, $remotePort, $localPort);
if (!$socket) {
die('Failed to create SSH tunnel');
}
// 使用 PDO 连接 MySQL
try {
$pdo = new PDO("mysql:host=localhost;port=$localPort;dbname=$dbname", $username, $password);
echo "Connected to the database successfully!";
} catch (PDOException $e) {
die('Connection failed: ' . $e->getMessage());
}
// 关闭 SSH 隧道
fclose($socket);
?>
通过以上步骤,你可以安全地通过 SSH 隧道连接 PHP 应用程序到 MySQL 数据库。
领取专属 10元无门槛券
手把手带您无忧上云