在PHP中通过SSH2进行PDO? [英] PDO via SSH2 in PHP?

查看:317
本文介绍了在PHP中通过SSH2进行PDO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问只能在本地(本地主机)访问的远程MySQL数据库.

I'm trying to access a remote MySQL Database which is only reachable locally (localhost).

我的代码如下:

$connection = ssh2_connect('IP to Server', 22);

    if (ssh2_auth_password($connection, 'User', 'Password')) {
        echo "Authentication Successful!\n";
    } else {
        die('Authentication Failed...');
    }

    $tunnel = ssh2_tunnel($connection, '127.0.0.1', 3306);

    try {
        $this->_connection = new PDO($dsn, $config['login'], $config['password'], $flags);
        $this->connected = true;
        if (! empty($config['settings'])) {
            foreach ($config['settings'] as $key => $value) {
                $this->_execute("SET $key=$value");
            }
        }
    } catch (PDOException $e) {
        throw new MissingConnectionException(array(
                'class' => get_class($this),
                'message' => $e->getMessage()
        ));
    }

脚本成功执行直到$ tunnel. PDO连接失败,并显示连接被拒绝".我认为PDO试图连接到MAMP? $ dsn变量看起来像"mysql:host = 127.0.0.1; port = 3306; dbname = mydb".

The script is successful till $tunnel. The PDO connection fails with "Connection refused". I think PDO is trying to connect to MAMP? The $dsn variable looks like "mysql:host=127.0.0.1;port=3306;dbname=mydb".

如何告诉MAMP,通过SSH连接的远程服务器上有127.0.0.1?

How can I tell MAMP, that 127.0.0.1 is on the remote server connected through SSH?

谢谢!

推荐答案

如上所述,您的脚本正在尝试连接到本地MySQL服务器,而不是远程服务器.为了使PDO与远程服务器建立连接,可以建立SSH tunnel并将本地端口转发到服务器端口.如此处所示 http://brettrawlins.com/mysql-ssh-tunnel/.

As you already noted, your script is attempting to connect to your local MySQL server instead of the remote one. In order for PDO to establish a connection with the remote server, you could establish an SSH tunnel and forward a local port to the server port. As shown here http://brettrawlins.com/mysql-ssh-tunnel/.

要在php中运行ssh命令:shell_exec(ssh code here)

To run the ssh command in php: shell_exec(ssh code here)

您可能希望看到:连接到MySQL服务器在PHP中通过SSH

尽管如此,该方法也相对较慢,因为每次查询数据库时都必须创建一个新的隧道,这会使查询花费更长的时间.我认为对于开发环境来说,这是一个有效的选择,因为您没有static IP,但我认为这在生产环境中不会起作用.

However as noted in there as well, this method is relatively slow as you will have to create a new tunnel each time you query the database, making your queries take quite a bit longer. I suppose for a development environment it's a valid option since you don't have a static IP, but I don't see this working in production.

如果您出于加密目的而尝试这样做,建议您使用SSL连接到数据库.但是请注意,PHP的所有版本可能不支持PDOSSL.

If you are trying to do this for the sake of encryption, I would recommend connecting to your database with SSL. However note that SSL for PDO might not be supported by all PHP versions.

这篇关于在PHP中通过SSH2进行PDO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆