Ask Your Question
0

How can Yii2 be connected to a remote MySQL database through SSH?

asked 2021-04-19 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-10-01 02:00:00 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-04-19 11:00:00 +0000

Seen: 19 times

Last updated: Oct 01 '21