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.
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
Asked: 2021-04-19 11:00:00 +0000
Seen: 20 times
Last updated: Oct 01 '21
What is an Ansible role that includes integrated modules?
How can records be counted from a category that is retrieved through another PHP and SQL query?
Why is the search function in PHP & MYSQL not providing relevant results?
What is the process to view and make edits to my complete MySQL code?
What is the method for showing errors in mysqli_query?
Is it impossible to generate a composer.lock file within a Docker container?