Connect to a MySQL server over SSH in PHP

I would use the autossh tool to create a persistent ssh tunnel to your mysql database. Then all you have to do in your PHP code is point it to localhost.

You can test this (without automatic restart) by doing:

ssh -L 3306:localhost:3306 [email protected]

Setup a ssh key so that you don’t need to use passwords, and tweak the .ssh/authorized_keys file on the mysql system to only allow it to be used for port forwarding.

For more info on ssh tricks see Brian Hatch’s excellent series on SSH and port forwarding.

Leave a Comment