Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To connect Yii2 to a remote MySQL database through SSH, follow these steps:

  1. Install the phpseclib library using Composer by executing the following command in your application directory:
composer require phpseclib/phpseclib
  1. Create a new PHP file in your application directory (e.g., 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();
  1. Replace the remote_host, username, and password values with the SSH credentials of your remote server.

  2. Replace the remote_mysql_host, database_name, database_username, and database_password values with the credentials of your MySQL database.

  3. 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.