I have my database on remote Linux machine, and I want to connect using SSH and PHP functions (I am currently using ssh2 library for that). I tried using mysql_connect, but it gives me can't access (although I have granted permission)
when I tried using this function:
$connection = ssh2_connect('SERVER IP', 22);
ssh2_auth_password($connection, 'username', 'password');
$tunnel = ssh2_tunnel($connection, 'DESTINATION IP', 3307);
$db = mysqli_connect('127.0.0.1', 'DB_USERNAME', 'DB_PASSWORD',
'dbname', 3307, $tunnel)
or die ('Fail: '.mysql_error());
I got error "mysqli_connect() expects parameter 6 to be string, resource given". How can I resolve this?
SSH Tunnel Solution
Set up an SSH tunnel to your MySQL database server (through a Jumpbox proxy for security).
(A) GUI Tools
Depending on your requirements, you can use a GUI MySQL client with SSH Tunnelling support built-in such as Visual Studio Code Forwarding a port / creating SSH tunnel, TablePlus or use PuTTY to setup local port forwarding.
On macOS, I like Secure Pipes or TablePlus.
(B) Command Line
Step 1.
ssh -fNg -L 3307:10.3.1.55:3306 username#ssh-jumpbox.com
The key here is the '-L' switch which tells ssh we're requesting local port forwarding.
I've chosen to use port 3307 above. All traffic on my local machine directed to this port will now be 'port-forwarded' via my ssh client to the ssh server running on the host at address ssh-jumpbox.com.
The Jumpbox ssh proxy server will decrypt the traffic and establish a network connection to your MySQL database server on your behalf, 10.3.1.55:3306, in this case. The MySQL database server sees the connection coming in from your Jumpbox' internal network address.
Local Port Forwarding Syntax
The syntax is a little tricky but can be seen as:
<local_workstation_port>:<database_server_addr_remote_end_of_tunnel>:<database_server_port_remote_end> username#ssh_proxy_host.com
If you're interested in the other switches, they are:
-f (go to background)
-N (do not execute a remote command)
-g (allow remote hosts to connect to local forwarded ports)
Private Key Authentication, add (-i) switch to above:
-i /path/to/private-key
Step 2.
Tell your local MySQL client to connect through your SSH tunnel via the local port 3307 on your machine (-h 127.0.0.1) which now forwards all traffic sent to it through the SSH tunnel you established in step 1.
mysql -h 127.0.0.1 -P 3307 -u dbuser -p passphrase
Data exchange between client and server is now sent over the encrypted SSH connection and is secure.
Security note
Don’t tunnel directly to your database server. Having a database server directly accessible from the internet is a huge security liability. Make the tunnel target address the internet address of your Jumpbox/Bastion Host (see example in step 1) and your database target the internal IP address of your database server on the remote network. SSH will do the rest.
Step 3.
Now connect up your PHP application with:
<?php
$smysql = mysql_connect( "127.0.0.1:3307", "dbuser", "passphrase" );
mysql_select_db( "db", $smysql );
?>
Credit to Chris Snyder's great article detailing ssh command line tunnelling for MySQL connectivity.
Unfortunately, the ssh2 tunnel offered by php doesn't seem able to handle a remote mysql connection as you cannot specify the local port to tunnel (it only works with port 22 or whatever ssh port your remote server is running on). My solution to this is to just open the tunnel via exec() operator and connect as usual from there:
exec('ssh -f -L 3307:127.0.0.1:3306 user#example.com sleep 10 > /dev/null');
$mysqli = new mysqli('127.0.0.1', 'user', 'password', 'database', '3307');
I was looking for the same thing, but I prefer not to need external commands and manage external processes. So at some point I thought, how hard can it be to write a pure PHP MySQL client which can operate on any PHP stream? It took me about half a day, based on the MySQL protocol documentation.
https://gist.github.com/UCIS/4e509915ed221660e58f5169267da004
You can use this with the SSH2 library or any other stream:
$ssh = ssh2_connect('ssh.host.com');
ssh2_auth_password($ssh, 'username', 'password');
$stream = ssh2_tunnel($ssh, 'localhost', 3306);
$link = new MysqlStreamDriver($stream, 'SQLusername', 'SQLpassword', 'database');
$link->query('SELECT * FROM ...')->fetch_assoc();
It does not implement the complete mysqli API, but it should work with all plain-text queries. Please be careful if you decide to use this, I haven't thoroughly tested the code yet and the string escaping code has not been reviewed.
According to the docs, that last parameter is supposed to be a socket or pipe name, something like '/var/run/mysql/mysql.sock'. Since you're not connecting using a UNIX socket, that doesn't apply to you... so try just leaving it out.
I believe that the reason I (and I suppose most people) have a problem getting this to work is because the user in the mysql server is set to only allow from "localhost" and not 127.0.0.1, the IP address of localhost.
I got this to work by doing the following steps:
Step 1: Allow 127.0.0.1 host for target user
SSH normally into your server, and log in with the mysql root user, then issue the command:
GRANT ALL ON yourdbname.* TO yourdbuser#127.0.0.1 IDENTIFIED BY 'yourdbpassword';
The key of course, is specifying 127.0.0.1 above.
Step 2: Start local SSH tunnel to MySQL
You can now start your local SSH tunnel to the remote MySQL server, like so:
ssh -vNg -L 33306:127.0.0.1:3306 sshuser#remotehost.com
-v makes ssh operate in verbose mode, which kind of helps to see what's happening. For example, you'll see debugging output like this in your terminal console when you attempt a connection:
debug1: client_input_global_request: rtype hostkeys-00#openssh.com want_reply 0
debug1: Connection to port 33306 forwarding to 127.0.0.1 port 3306 requested.
and output like this when you close the connection:
debug2: channel 2: is dead
debug2: channel 2: garbage collecting
debug1: channel 2: free: direct-tcpip: listening port 33306 for 127.0.0.1 port 3306, connect from 127.0.0.1 port 52112 to 127.0.0.1 port 33306, nchannels 3
-N makes ssh issue no commands, and just wait instead after establishing connection.
-g allows remote hosts to connect to local forwarded ports. Not completely sure if this is necessary but it might be useful for multiplexing multiple connections through the same SSH tunnel.
-L This is the main parameter that specifies the local port 33306 to connect to the remote host's local IP address 127.0.0.1 and the remote host's mysql port, usually 3306.
You can use whatever mechanisms / other parameters needed after this to connect through SSH to your remote host. In my case, I use key files configured in my ~/.ssh/config so I just need to specify user#host to get in.
Issuing the command like this runs SSH in the foreground, so I can easily close it with Ctrl + C. If you want to run this tunnel in a background process you can add -f to do this.
Step 3: Connect from PHP / other mysql compatible methods
The SSH tunnel running from above on your localhost will behave exactly like as if your mysql was running on 127.0.0.1. I use port 33306 (note the triple 3) which lets me run my local sql server at its normal port. You can now connect as you would normally do. The mysql command on the terminal looks like this:
mysql -h 127.0.0.1 -P 33306 -u yourmysqluser -p
where -P (capital P) specifies the port where your SSH tunnel's local end is accepting connections. It's important to use the 127.0.0.1 IP address instead of localhost because the mysql cli will try to possibly use the linux socket to connect.
For PHP connection strings, my data source name string (for my Yii2 config) looks like this:
'dsn' => 'mysql:host=127.0.0.1;dbname=yourdbname;port=33306',
Passwords, and usernames are specified as normal.
even i tried it by doing ssh both by root credentials and and public private key pair, but it allows me to conect through command line but not through php code. I tried by creating tunnel also(by using ssh2 functions),ans running shell commands from php code(system,exec etc), nothing worked. Finally i tried ssh2 function to execute shell command and it finally worked :) Here is code, if it helps you:----
$connection = ssh2_connect($remotehost, '22');
if (ssh2_auth_password($connection, $user,$pass)) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
$stream=ssh2_exec($connection,'echo "select * from zingaya.users where id=\"1606\";" | mysql');
stream_set_blocking($stream, true);
while($line = fgets($stream)) {
flush();
echo $line."\n";
}
it worked for me try this if want to use php functions specifically.
Make sure that your username and password that you are connecting with has the right hostname permissions. I believe you can use '%' for a wildcard. Also if you are connecting to remote machine (which I would assume you are if you are trying to ssh into it) that is not on your local network you will have to forward the ports on your router where the server is for outside traffic to be able to connect to it.
http://www.lanexa.net/2011/08/create-a-mysql-database-username-password-and-permissions-from-the-command-line/
When using ssh2 to connect, since there is no special function for php to use ssh2 to connect to mysql, we can only use the traditional socket and mysql protocol for data interaction.
When we use the ssh2_tunnel method, if the creation is successful, a socket object will be returned, then we can use this socket object for mysql data interaction. Of course, we need to understand the mysql protocol, which is the so-called "handshake packet"
......
$tunnel = ssh2_tunnel(....)
......
//we need to construct the mysql data packet and then use fwrite to transfer this packet to mysql host
fwrite($tunnel, MYSQLDATAPACKET)
when we use ssh2_connect method to connect the mysql host, it will return a MySQL handshake packet, it looks like this:
a 5.5.5-10.3.34-MariaDB-cll-lve�WfyP`uKW����RtscuF:/}J7umysql_native_password!��
here is the mysql handshake packet structure:
size(byte) description
1 protocol version
n server version
4 connection id
8 auth-plugin-data-part-1
1 filler
2 capability flags
1 character set
2 status flags
2 capability flags
1 length of auth-plugin-data
10 reserved
13 auth-plugin-data-part-2
n auth-plugin name
so we should parse the byte array by using such structure.
After receving the Mysql handshake, which means we have connected the mysql host, and now we need to login mysql, so we need to construct the mysql send data packet
here is the data structure: (HandshakeResponse41)
4 capability flags, CLIENT_PROTOCOL_41 always set
4 max-packet size
1 character set
string[23] reserved (all [0])
string[NUL] username
if capabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA {
lenenc-int length of auth-response
string[n] auth-response
} else if capabilities & CLIENT_SECURE_CONNECTION {
1 length of auth-response
string[n] auth-response
} else {
string[NUL] auth-response
}
if capabilities & CLIENT_CONNECT_WITH_DB {
string[NUL] database
}
if capabilities & CLIENT_PLUGIN_AUTH {
string[NUL] auth plugin name
}
if capabilities & CLIENT_CONNECT_ATTRS {
lenenc-int length of all key-values
lenenc-str key
lenenc-str value
if-more data in 'length of all key-values', more keys and value pairs
}
See Also: https://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::HandshakeResponse41
Okay, so we have connected the mysql host successfully, and then you can query the database.
Here is the sample code for the Mysql Handshake and Mysql Socket Login:
function parseMysqlHandshakePack($hex_string)
{
$dataField = {
"protocol_version" => "",
"server_version" => "",
"thread_id" => "",
"salt1" => "",
"salt2" => "",
"salt" => "",
}
$dataField["protocol_version"] = UtiliHelper::HexToInt(UtiliHelper::HexSub($hex_string,0,1));
$dataField["server_version"] = UtiliHelper::HexToStr(UtiliHelper::HexSub($hex_string,1,7));
$dataField["thread_id"] = UtiliHelper::HexToInt(UtiliHelper::HexSub($hex_string,8,4));
$dataField["salt1"] = UtiliHelper::HexSub($hex_string,12,8);
$dataField["salt2"] = UtiliHelper::HexSub($hex_string,39,12);
$dataField["salt"] = $dataField["salt1"] . $dataField["salt2"];
return $dataField;
}
function constructMysqlLoginPacket($username, $password, $database, $salt){
$tags = [
"power_tag" => "",
"power_ext" => "",
"max_length" => "",
"charset" => "",
"fill_pad" => "",
"username" => "",
"password" => "",
"database" => "",
"client_auth_plugin" => "",
"payload" => ""
];
$tags['power_tag'] = "8da2";
$tags['power_ext'] = "0b00";
$tags['max_length'] = "000000c0";
$tags['charset'] = "08";
$tags['fill_pad'] = "0000000000000000000000000000000000000000000000";
$tags['client_auth_plugin'] = "6d7973716c5f6e61746976655f70617373776f726400";
$tags["payload"] = "150c5f636c69656e745f6e616d65076d7973716c6e64";
$tags['username'] = UtiliHelper::StrToHex($username)."0014";
$tags['password'] = UtiliHelper::encryptionPass($password,$salt);
$tags['database'] = UtiliHelper::StrToHex($database)."00";
$message = "";
foreach ($tags as $tagv){
$message .= $tagv;
}
return UtiliHelper::IntToHex(strlen($message)/2)."01".$message;
}
the $salt parameter came from the Handshake phase, so you need to parse the mysql handshake message and get the salt.
The UtiliHelper is a custom class which is from a 3rd party party project in Github: https://github.com/gphper/PHPMysql/blob/master/src/UtiliHelper.php
Related
For my University project I am connecting to a MySQL database. As of covid 19 I can't go to uni so have to do it remotely can anyone help with the PHP connection?
SSH Hostname: ssh.University.uk:2223
SSH Username: s4905304
SHH Password: ....
SSH Key File:blank
MySQL Hostname: 127.0.0.1
MySQL Server Port:3306
Username:s4905304
Password:.....
Try this:
Step 1.
Set up an SSH tunnel to your MySQL database server (preferably, through a Jumpbox for security).
ssh -fNg -L 3307:10.3.1.55:3306 username#ssh_jumpbox.com
The key here is -L which says we're doing local port forwarding.
Local Port Forwarding Syntax
<local_workstation_port>:<database_server_addr_remote_end_of_tunnel>:<database_server_port_remote_end>
username#ssh_proxy_host.com
Other switches are:
-f (go to background)
-N (do not execute a remote command)
-g (allow remote hosts to connect to local forwarded ports)
Private Key Authentication, add (-i) switch to above:
-i /path/to/private-key
Step 2.
Tell your local MySQL client to connect through your SSH tunnel via the local port 3307 on your machine (-h 127.0.0.1) which now forwards all traffic sent to it through the SSH tunnel you established in step 1.
mysql -h 127.0.0.1 -P 3307 -u dbuser -p passphrase
Data exchange between client and server is now sent over the encrypted SSH connection and is secure.
Tunneling directly to your database server is not recommended - having a database server directly accessible from the internet is a huge security liability. Make the tunnel target address the internet address of your Jumpbox/Bastion Host (see example in step 1) and your database target the internal IP address of your database server on the remote network. SSH will do the rest.
Credit to Chris Snyder's great article at http://chxo.com/be2/20040511_5667.html
Step 3.
Connecting. DSN
PDO has a fancy connection method called DSN. It's nothing
complicated though - instead of one plain and simple list of options,
PDO asks you to input different configuration directives in three
different places:
database driver, host, db (schema) name and charset, as well as less frequently used port and unix_socket go into DSN;
username and password go to constructor;
all other options go into options array.
where DSN is a semicolon-delimited string, consists of param=value
pairs, that begins from the driver name and a colon:
mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4
driver^ ^ colon ^param=value pair ^semicolon
Note that it's important to follow the proper format - no spaces or
quotes or other decorations have to be used in DSN, but only
parameters, values and delimiters, as shown in the manual.
Here goes an example for MySQL:
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
Quoted from: https://phpdelusions.net/pdo#dsn
How to connect linux server from PHP through intermediate server.
Local Machine(A) --> Intermediate Server (linux machine)(B) --> Linux Machine(C)
I want to connect A->B then B->C system.
I have used below code.
$connection = ssh2_connect('121.2.3.11', 22); //
ssh2_auth_pubkey_file($connection, 'username', 'id_dsa.pub', 'id_dsa'); // (B) system connection
$tunnel = ssh2_tunnel($connection, '121.2.3.12', 12345); // (C) system connection
Here, where to give username/password for C ("121.2.3.12") system.
You've copied and pasted the example from the manual without apparently reading/understanding what ssh2_tunnel does.
You seem to be expecting that ssh2_tunnel creates an ssh connection - it doesn't. It creates a raw TCP socket connection which tunnelled through an existing ssh connection.
Do you actually have an ssh server listening on port 12345?
While there are sometimes good reasons for tunnelling an ssh connection inside an ssh connection, these are very unusual cases and there's no evidence that they apply here. If they don't apply, then ssh inside ssh is very innefficient and you should be relaying the connection instead. I'm not sure quite how you would do that as most ssh logins clear the input buffered, so you'd need to poll/respond to the prompt.
You've got no error checking in the code you've shown us. You should be checking the return values from each of the functions to check they were successful.
I have an application in which I have to access all pc connected to same network and their MySql Databases and I also want want to connect to remotely a server.
Actually I have list of drop down services and each service holding a database name. when I select a service then I want to build connection to database either it lies on same network or any remote server.
Remember, I know the hostname, username, password and dbname. and I am using mysqli_connect function.
I have try multiple options given on web, but all in vain. e.g grant host and user access. But not found any solution can help to solve my problem.
I have try bind-address option in my.conf file but no solution.
Here is my code
For remote Server
$con = new mysqli_connect('xxx xxx xxx:3306', 'username', 'pass', 'dbname');
For local Network
$con = new mysqli_connect('xxxx xxx xxx:3306', 'localhost', '', 'talent');
Error
mysqli::mysqli();(HY000/2002): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. and also get this one earlier Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'#'localhost' (using password: YES).
I am using windows platform. WIndow 8.1
I guess you want to access mysql database installed on different computers on same network as your computer and also on some remote server.
What you need is IP Addresses of all the computers on which the mysql server is installed including the remote server. And on each such computer mysql server remote access should be enabled for your computer's IP Address and mysql user you are using in 'new mysqli_connect()'. See this tutorial.
Also as fvu said check php documentation for 'mysqli_connect' function.
UPDATED
What is SSH?
1. SSH is SecureSHell.
2. Its nothing but a remote login tool or program(like telnet but in secured way).
3. Remote login is logging in to some other computer(known as remote computer) as a user of that computer from your computer.
4. After you successfully logged in to the remote computer via ssh, you can type commands on that remote computer on behalf of the user you are loggen in with.
5. Consider this as if you are sitting in front of your computer and watching the command prompt(terminal in linux and mac) screen of the remote computer.
6. Whataver you will type here will reflect there.
For your knowledge to make you understand the problem:
1. When you install XAMPP or WAMP on your computer it also installs MySQL Server with it.
2. MySQL Server is a process running in the background to which we can request to do
database operations like SELECT, UPDATE, etc.
3. This thing we generally do using 'mysql_connect' or 'mysqli_connect' in php.
4. MySQL Server can have many users and different users have different previledges/permissions. So that MySQL admin user(i.e. root) can control what things are allowed and not allowed for a user.
5. Now while connecting to the mysql server process we need to specify the user credentials. That you specify in mysqli_connect function.
Now let me explain you why you are getting that error:
1. The user credentials you are using either does not exist or not correct or the user has no access to connect to MySQL Server process remotely. i.e. from other computer that the one has MySQL Server installed on. In your case from your computer to computer A or to computer B or remote server.
2. The other reason may be the firewall settings of remote computers.
Solution:
1. For computer A and computer B you don't need ssh you can directly go to the computer and open command prompt on it and type commands.
2. But for remote computer you need to use ssh.
3. Now another problem is you are using Windows so ssh program will not be available to you.
4. You will need to download putty program. Its ssh implementation for windows. Same as ssh only name is different.
5. Take a putty tutorial to connect to remote server.
6. Then you can use this tutorial for granting remote login access to mysql user you are using in mysqli_connect function.
If the server is a local hosted database and you can connect to it from local host and i you are not able to connect to it from a remote machine consider the following options.
There is a firewall in ubuntu that you need to open, you do this by granting access in IPtables.
/sbin/iptables -A INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT And now we should be able to login to our server from our local machine:
mysql -h255.112.324.12 -uroot -pMyPASSWORD
You need
to grant access to mysql: https://askubuntu.com/questions/159053/mysql-server-not-accessible-from-remote-machine
as root, open your /etc/mysql/my.cnf with your favorite editor look for the [mysqld] section, and in there for the bind-address keyword. This usually is set to 127.0.0.1 -- change that to match your "normal" IP-address save the file, and reload the service (e.g. using service mysql restart)
Last but not least you need to give remote access in mysql:
GRANT ALL ON mydb.* TO root#'%' IDENTIFIED BY 'MyPASSWORD';
Find more information here: http://web.archive.org/web/20120930214828/http://chosencollective.com/technology/how-to-enable-remote-access-to-mysql
Right now you seem to be mixing object-oriented and procedural approaches. If you want to use object-orented approach, mysqli object should be instantiated as follows:
$con = new mysqli($host, $username, $password, $dbname, $socket); // all but first parameter are optional
If you want to use procedural approach, mysqli connection resource should be created as follows:
$con = mysqli_connect($host, $username, $password, $dbname, $socket); // all but first parameter are optional
I have a MySQL database, hosted by me on a Windows server, and I would like to query it from a remote webserver. When I try to connect to the MySQL database using PHP (I know, I should be using mysqli):
$connection = #mysql_connect("203.0.113.0:3306", "username", "password");
With or without specifying the port, after a long time of loading, I get this error with an errorno of 2003:
Can't connect to MySQL server on '203.0.113.0' (4)
Here is what I get when I run netstat -n in command prompt on the server that is hosting the MySQL server: http://pastebin.com/pbRJNqCZ. It filled up the screen so I couldn't copy everything, but I know that everything else was (I saw a couple ports with a value of 3306, which is the MySQL port):
TCP 127.0.0.1:port 127.0.0.1:port ESTABLISHED
When I run netstat -a | find "LISTENING" I get: http://pastebin.com/Lqj2BrQK
Here's what I know so far:
It isn't an error with the MySQL server not being up, because I can connect to it locally.
It isn't an error with the webserver not being able to connect to MySQL databases, because I can connect to other databases
It isn't an authentication error (The username and password are correct, and the remote server has permission)
It isn't a port forwarding error, because the port 3306 is fowarded on both TCP & UDP.
It isn't an error with being able to connect to the machine the server is hosted on, because I can ping it fine.
The server isn't only listening on the localhost interface. skip-networking and bind-address are commented out in my my.cnf file.
How could I edit my connection code, or edit my MySQL server to fix this error?
Summarizing our discussion/chat:
Bind the network address 0.0.0.0 in my.cnf: bind-address = 0.0.0.0 and ensure skip-networking is commented out or not present.
Check netstat -a | find "LISTENING"
According to your pastebin there is a service listening on 3306. Test if the port is reachable on the NIC address from the server itself. This way an external firewall does not take effect. A simple test is to try a telnet connection to that port. More detailed information can be catched by the tool nmap. Nmap has displayed the mysql port as filtered. This adverts to a problem with a local packet filter, in this case the Windows firewall.
Ensure the Windows firewall is configured to allow public access to TCP port 3306 from all or a specific machine. Setup a rule in public profile or, if both servers are controled by the same domain controller, in domain profile. When the access from local machine is successful try the same from the remote web server.
If you fail to properly configure remote access to MySql port, consider to establish a SSH tunnel between the two machines. Once established you can access to MySql as if it were on the local machine. The port is then forwarded via the tunnel and on the database server side you can access the service on localhost loopback IP.
I've got a web server with one host, and I'd like to use the database on another host.
I'd like to use port forwarding to do this, and have already set up the forwarded port using
ssh -P -fg -L23307:myserver.net:3306 myname#myserver.net sleep 1d
This seems to be working properly (although if someone could tell me how to check, that would be great), but I can't get PHP to connect to MySQL through that port - it keeps trying to connect to its own local MySQL database (which isn't running).
$mlink = mysql_connect( "localhost:23307", "myusername", "mypassword" );
mysql_select_db( 'mydatabase', $mlink ) or die ( "Error - cannot connect to database localhost:23307.<br />Error: ".mysql_error() );
As you can see, I'm not doing anything that complicated, so why does it keep trying to connect locally?
So, turns out the answer was "don't trust people when they say they've opened the port on the firewall".
Anyone want a job?
I faced the same issue. But there was no firewall problem involved. In fact, when you are doing SSH tunneling, you need not have to change any firewall setting.
I solved it by changing 'localhost' to '127.0.0.1' in the mysql_connect() parameter list.
Refernce link - https://blog.rjmetrics.com/2009/01/06/php-mysql-and-ssh-tunneling-port-forwarding/
Excerpt -
Connecting via MySQL
It’s time to see all of our hard work pay off. From our local machine, we simply issue the following command:
$mysql -u sqluser -p -h 127.0.0.1 -P 3307
Notice that the MySQL host is 127.0.0.1, which is the same as the bind-address value on the remote server’s my.cnf file. It’s important that we use this value and not localhost, since we are ultimately accessing a forwarded TCP port, and specifying localhost causes MySQL to ignore TCP altogether and simply connect to the local server via a local socket. Accordingly, notice that we have specified port 3307 to make the connection; this is the TCP port we are forwarding.