0

Can anyone help with a config.php example to connect a Yii2 app running on one host to a remote host MySQL server through SSH. I have only ever run MySQL on the same localhost as the app itself, with a db.php config something like this:

<?php
return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;port=3306;dbname=mylocaldb',
    'username' => 'auser',
    'password' => 'apassword',
    'charset' => 'utf8',
];

How do I specify the SSH tunnel, i.e., its host name and RSA key file? Don't see anything in the yii\db\Connection API that gives me a clue. Is this even possible?

Thanks in advance.

Joe

Papa Joe Dee
  • 303
  • 4
  • 13
  • Did you try ? `'dsn' => 'mysql:dbname=remote_db_name;host=remote_ip_here';` – Indra Kumar S Mar 09 '23 at 07:07
  • That would only work if the mysql server is exposed to remote connections and the mysql user is set to allow remote access. The OP is asking for SSH tunnel, probably because they can't access the remote DB directly. There are two ways to solve the issue: 1. create the permanent ssh tunnel outside of PHP script. 2. create temporary ssh tunnel with `shell_exec` or `exec` in php code before opening the DB connection. For the second option you might need to extend `yii\db\Connection` to run your code before opening db connection. – Michal Hynčica Mar 09 '23 at 11:16
  • Try checking these answers: https://stackoverflow.com/a/12660234/11977068 and https://stackoverflow.com/a/47407471/11977068. Also, be careful about `host=localhost` vs `host=127.0.0.1` in your DSN. When you use `host=localhost` the PDO might prefer using UNIX socket instead of TCP/IP one and it won't be able to connect to tunnel listening on TCP port XXXX. – Michal Hynčica Mar 09 '23 at 11:24

0 Answers0