使用 PHP 使用 SSH 连接到远程 MySQL 数据库
我有一个远程数据库,我想从本地运行的 PHP 连接到。数据库不允许远程连接,所以通常我通过 SSH 进入盒子并从命令行使用它,但这并不是一个真正的长期解决方案。
我有 SSH 访问权限,一旦 SSH 进入,我就可以访问 MySQL,但我不知道如何让 PHP 进入该工作流程。如果我可以在 MAMP 中完成这项工作,那就太好了。
I have a remote database I'd like to connect to from PHP running locally. 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.
I have SSH access, I have MySQL access once I SSH in, but I don't know how to get PHP into that workflow. If I could make this work within MAMP, that would be great, too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
开发或测试时,可以使用ssh命令先建立隧道,然后像本地数据库一样访问远程数据库。步骤是:
1) 使用 ssh 命令设置隧道。命令格式:ssh -L [本地端口]:127.0.0.1:[远程mysql端口,默认为3306] [用户]@[远程mysql服务器ip]。样本:
ssh -L 3307:127.0.0.1:3306 [电子邮件受保护]
2)保持命令窗口处于活动状态
3) 您可以通过 mysql 字符串访问远程数据库: mysqli://[用户]:[密码]@127.0.0.1:3307/[数据库名称]
For developing or testing, you can use ssh command to setup tunnel first and then access the remote database as a local one. The steps are:
1) setup tunnel with ssh command. command format: ssh -L [local port]:127.0.0.1:[remote mysql port, by default, it is 3306] [user]@[remote mysql server ip]. sample:
ssh -L 3307:127.0.0.1:3306 [email protected]
2) keep the command window alive
3) You can access the remote database by mysql string: mysqli://[user]:[password]@127.0.0.1:3307/[database name]
在 PHP 中通过 SSH 连接到 MySQL 服务器
Connect to a MySQL server over SSH in PHP
您可以设置 SSH 隧道,然后将 php 连接代码指向通过隧道转发的本地端口。在 Windows 下你可能会使用 putty;对于 Mac 也会有类似的解决方案。
You could set up a SSH tunnel and then point your php connection code to a local port which is forwarded through the tunnel. Under Windows you might use putty; for Mac there will be similar solutions.
如果这是为了开发,亚历克斯建议的解决方案是可行的方法;设置 ssh 隧道。
隧道会将您的 127.0.0.1:3306 请求重定向到远程计算机。远程计算机也会相信请求来自 127.0.0.1(本地)。
但是,如果您的服务器(共享主机?请指定)不允许来自 127.0.0.1 的 mysql 连接(通常只允许 localhost),您可能会遇到问题。它们之间存在微小的差异,它会阻止您的隧道到达远程 mysqld。
只需谷歌隧道,设置它,并使用 php 连接字符串中的 127.0.0.1 即可。
问候,
//t
If this is for development, the suggested solution by alex is the way to go; set up a ssh-tunnel.
The tunnel will redirect your 127.0.0.1:3306-requests to the remote machine. The remote machine will also belive the requests will come from 127.0.0.1 (locally).
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). There's a tiny difference in those, and it will inhibit your tunnel from reaching the remote mysqld.
Just google tunneling, set it up, and use 127.0.0.1 from your php-connection strings.
regards,
//t