1 | initial version |
To connect Yii2 to a remote MySQL database through SSH, follow these steps:
composer require phpseclib/phpseclib
ssh.php
) and add the following code:<?php
require_once 'vendor/autoload.php';
use phpseclib\Net\SSH2;
$ssh = new SSH2('remote_host');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
$ssh->setTimeout(5);
$port = $ssh->exec('echo $SSH_CLIENT');
$port = explode(' ', $port)[2];
$port = explode(':', $port)[1];
$ssh->exec("ssh -f -L {$port}:remote_mysql_host:3306 -N");
$connection = new \yii\db\Connection([
'dsn' => 'mysql:host=127.0.0.1;port='.$port.';dbname=database_name',
'username' => 'database_username',
'password' => 'database_password',
]);
$connection->open();
Replace the remote_host
, username
, and password
values with the SSH credentials of your remote server.
Replace the remote_mysql_host
, database_name
, database_username
, and database_password
values with the credentials of your MySQL database.
Call the ssh.php
file in your Yii2 application to establish a connection to the remote MySQL database through SSH.
Note: Make sure that the remote MySQL database is configured to accept connections from the SSH tunnel's IP address.