среда, 17 октября 2012 г.

PHP SSH MYSQL


The tunnel must be keep open, the following example from RJMetrics explains:
Here’s how to securely establish a remote database connection in just 2 lines of PHP code:
shell_exec(“ssh -f -L 3307:127.0.0.1:3306 user@remote.rjmetrics.com sleep 60 >> logfile”);  
$db = mysqli_connect(’127.0.0.1′, sqluser’, sqlpassword’, rjmadmin’, 3307);
We use the shell_exec function to create the tunnel with a 60 second opening window, and then use the mysqli_connect function to open a database connection using the forwarded port. Note that we must use the “mysqli” library here because mysql_connect does not allow us to specify a port.
sleep 60: When it comes to tunnel connections, we basically have two options: leave the connection open all the time or open it and close it as needed. We prefer the latter, and as such we don’t specify the “-N” option when establishing a tunnel, which would leave it open until the process is manually killed (bad for automation). Since “-N” is not specified, our tunnel will close itself as soon as its SSH session isn’t being used for anything. This is ideal behavior, except for the few seconds between when we create the tunnel and when we get a MySQL connection up and running via the tunnel. To buy us some time during this period, we issue the harmless “sleep 60″ command when the tunnel is created, which basically buys us 60 seconds to get something else going through the tunnel before it closes itself. As long as a MySQL connection is established in that timeframe, we are all set.