2013-08-05 206 views
4

我已经写了一个php文件,连接到本地mysql数据库。现在,我想通过SSH连接到远程数据库。目前我的数据库连接功能在PHP中的以下内容:通过PHP连接到mysql数据库通过PHP

$this->db = new mysqli(_SERVR_URL, _SERVR_USER , _SERVR_PASS, _SERVR_DB); 
    if ($this->db->connect_errno) { 
     echo "Failed to connect to MySQL: (" . $this->db->connect_errno . ") " . $this->db->connect_error; 
    } 
    else{ 
     //echo "Successfully connected!! <BR><BR>"; 
    } 

我想只改变连接功能(上图),这样的代码的其余部分仍然有效。我已经成功安装了phpseclib,并且对安装php的ssh扩展并不感兴趣,因为经过近5个小时的努力后,这些扩展并不能正常工作。 phpseclib正在工作,我认为这是因为当我使用require时,它不会死亡。

然而,当我尝试启动使用ssh的东西的工作,它抛出一个服务器错误:

$ssh = new Net_SSH1(myURL); 

,我通常SSH到我的服务器是为.pem文件的方式。我可以得到一些指导:

  1. 为什么当前的代码可能会引发错误?
  2. 如果这是可能的。
  3. 您将如何使用.pem文件编写连接代码。
+0

复制http://stackoverflow.com/questions/309615/connect-to-a-mysql-server-over-ssh-in:当时的想法是在PHP内部邮件列表前阵子讨论-php – kwarunek

+1

它不是重复的。他们不需要使用.pem文件,他们也没有特别要求关于phpseclib库。 – Lugubrious

回答

4

I think you are out of luck on this one. You can either use the ssh extension in your PHP code, or if you have access to the server, you could try to create a ssh tunnel on the command-line.

You probably need special permissions to do that, though. It also looks like you don't have ssh access to this hosting account.

duplicateConnect to a MySQL server over SSH in PHP

而且this one回答@jpm

Setting up tunneling发表@奥拉维尔Waage的隧道通过@Sosy

shell_exec(“ssh -f -L 3307:127.0.0.1:3306 [email protected] sleep 60 >> logfile”); 
$db = mysqli_connect(’127.0.0.1′, ‘sqluser’, ‘sqlpassword’, ‘rjmadmin’, 3307); 
+0

编辑:只看到你的编辑。 感谢隧道帮助 - 这实际上是安全的吗? – Lugubrious

+0

但是,它可能会造成一些漏洞,某些系统错误无法在php中处理,它可能会导致系统错误与简单易用 – kwarunek

+0

我的php脚本不会创建ssh隧道,但是当我在终端中创建它时该代码将在指定的时间内运行。为什么会发生这种情况? – Lugubrious