Connect to a MySQL server over SSH in PHP

Connect to a MySQL server over SSH in PHP

Sometimes you may need to connect with a remote database over ssh from a PHP project. How you can do it. Here I am showing you the way. I made the connection for a laravel project. First thing first, before start you have to have an ssh connection with your server. For example- when you type: ssh username@IP it should get access to your server. If you are unable to access configure it. Now you need to change your database config like is: DB_CONNECTION=mysql DB_HOST=127.0.0.1:3311 DB_PORT=3306 DB_DATABASE= your_db DB_USERNAME=your_user DB_PASSWORD=your_password Here I used 3311 port with 127.0.0.1. This because later I'll create an ssh tunnel and bind the port with it. My remote server MySQL port is 3306. Now let's create an ssh tunnel by the following command - ssh -N -L 3311:127.0.0.1:3306 yourusername@IP -L which tells ssh we're requesting local port forwarding. -N Do not execute a remote command. This is useful for just forwarding ports (protocol version 2 only). After running the above ssh command now try to connect with DB. It should successfully connect with the remote server. If you face any problem let me know by comment.

Be the first person to like this