简体   繁体   English

使用SSH通过PHP连接到远程MySQL数据库

[英]Connect to remote MySQL database with PHP using SSH

I have a remote database I'd like to connect to from PHP running locally. 我有一个远程数据库,我想从本地运行的PHP连接到。 The database doesn't allow remote connections so ordinarily I SSH into the box and use it from the command line, but that's not really a long term solutions. 数据库不允许远程连接,所以通常我通过SSH进入框并从命令行使用它,但这不是一个长期的解决方案。

I have SSH access, I have MySQL access once I SSH in, but I don't know how to get PHP into that workflow. 我有SSH访问权限,一旦我进入SSH,我就有MySQL访问权限,但我不知道如何让PHP进入该工作流程。 If I could make this work within MAMP, that would be great, too. 如果我能在MAMP内完成这项工作,那也很棒。

For developing or testing, you can use ssh command to setup tunnel first and then access the remote database as a local one. 对于开发或测试,您可以使用ssh命令首先设置隧道,然后以本地数据库的形式访问远程数据库。 The steps are: 步骤是:

1) setup tunnel with ssh command. 1)使用ssh命令设置隧道。 command format: ssh -L [local port]:127.0.0.1:[remote mysql port, by default, it is 3306] [user]@[remote mysql server ip]. 命令格式:ssh -L [本地端口]:127.0.0.1:[远程mysql端口,默认为3306] [user] @ [remote mysql server ip]。 sample: ssh -L 3307:127.0.0.1:3306 ford@134.11.21.89 示例:ssh -L 3307:127.0.0.1:3306 ford@134.11.21.89

2) keep the command window alive 2)使命令窗口保持活动状态

3) You can access the remote database by mysql string: mysqli://[user]:[password]@127.0.0.1:3307/[database name] 3)您可以通过mysql字符串访问远程数据库:mysqli:// [user]:[password] @ 127.0.0.1:3307 / [数据库名称]

You could set up a SSH tunnel and then point your php connection code to a local port which is forwarded through the tunnel. 您可以设置SSH隧道,然后将您的php连接代码指向通过隧道转发的本地端口。 Under Windows you might use putty; 在Windows下你可以使用putty; for Mac there will be similar solutions. 对于Mac,会有类似的解决方案。

If this is for development, the suggested solution by alex is the way to go; 如果这是用于开发,亚历克斯建议的解决方案是要走的路; set up a ssh-tunnel. 建立一个ssh隧道。

The tunnel will redirect your 127.0.0.1:3306-requests to the remote machine. 隧道会将您的127.0.0.1:3306-请求重定向到远程计算机。 The remote machine will also belive the requests will come from 127.0.0.1 (locally). 远程机器也将相信请求将来自127.0.0.1(本地)。

However, you may encounter problems if your server (shared host? please specify) doesn't allow mysql-connections from 127.0.0.1 (quite commonly only localhost are allowed). 但是,如果您的服务器(共享主机?请指定)不允许来自127.0.0.1的mysql连接(通常只允许使用localhost),则可能会遇到问题。 There's a tiny difference in those, and it will inhibit your tunnel from reaching the remote mysqld. 这些之间存在细微差别,它会阻止您的隧道到达远程mysqld。

Just google tunneling, set it up, and use 127.0.0.1 from your php-connection strings. 只需谷歌隧道,设置它,并从您的PHP连接字符串使用127.0.0.1。

regards, 问候,

//t //Ť

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

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