简体   繁体   English

在mysql_connect上使用端口转发和php到远程服务器上

[英]Using port forwarding and php with mysql_connect onto a remote server

I've got a web server with one host, and I'd like to use the database on another host. 我有一台具有一台主机的Web服务器,我想在另一台主机上使用该数据库。 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). 这似乎工作正常(尽管有人告诉我如何检查,那很好),但是我无法让PHP通过该端口连接到MySQL-它一直尝试连接到自己的本地MySQL数据库(它没有运行)。

$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. 实际上,在进行SSH隧道传输时,无需更改任何防火墙设置。

I solved it by changing 'localhost' to '127.0.0.1' in the mysql_connect() parameter list. 我通过在mysql_connect()参数列表中将'localhost'更改为'127.0.0.1'来解决此问题。 Refernce link - https://blog.rjmetrics.com/2009/01/06/php-mysql-and-ssh-tunneling-port-forwarding/ Refernce链接- https://blog.rjmetrics.com/2009/01/06/php-mysql-and-ssh-tunneling-port-forwarding/

Excerpt - 摘录-

Connecting via MySQL 通过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 $ 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. 请注意,MySQL主机是127.0.0.1,与远程服务器的my.cnf文件上的bind-address值相同。 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. 重要的是,我们使用此值而不是localhost,因为我们最终将访问转发的TCP端口,并且指定localhost会使MySQL完全忽略TCP并仅通过本地套接字连接到本地服务器。 Accordingly, notice that we have specified port 3307 to make the connection; 因此,请注意,我们已指定端口3307进行连接; this is the TCP port we are forwarding. 这是我们正在转发的TCP端口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM