Skip to content

Instantly share code, notes, and snippets.

@vertexvaar
Last active November 29, 2016 23:17
Show Gist options
  • Save vertexvaar/652c306086748818f1ecb4f4b53ab169 to your computer and use it in GitHub Desktop.
Save vertexvaar/652c306086748818f1ecb4f4b53ab169 to your computer and use it in GitHub Desktop.
How to establish a SSH local forward with PHP and connect to a remote DB afterwards
<?php
$proc = new \Symfony\Component\Process\Process(
'\\ssh -i ' . $pk . ' -NL 3307:' . $dbServ . ':3306 ' . $sshUsr . '@' . $sshHst . ' sleep 10 >> logfile'
);
$proc->start();
// wait until connection is established
sleep(1);
$dataBase = new \mysqli('127.0.0.1', $dbUsr, $dbPwd, $dbName, 3307);
$result = false;
if ($dataBase->errno === 0) {
$query = $dataBase->query('show databases');
$result = $query->fetch_all(MYSQLI_ASSOC);
}
// !!! This does not destroy the port forwarding !!!
$proc->stop();
return $result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment