无法让 SFTP 在 PHP 中工作 [英] Can't get SFTP to work in PHP

查看:115
本文介绍了无法让 SFTP 在 PHP 中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 PHP 编写一个简单的 SFTP 客户端,因为我们需要通过 n 个远程服务器以编程方式检索文件.我使用的是 PECL SSH2 扩展.

I am writing a simple SFTP client in PHP because we have the need to programatically retrieve files via n remote servers. I am using the PECL SSH2 extension.

不过,我遇到了路障.php.net 上的文档建议您可以这样做:

I have run up against a road block, though. The documentation on php.net suggests that you can do this:

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

但是,我有一个 ls 方法可以尝试类似的东西

However, I have an ls method that attempts to something similar

public function ls($dir)
{
    $rd = "ssh2.sftp://{$this->sftp}/$dir";
    $handle = opendir($rd);
    if (!is_resource($handle)) {
        throw new SFTPException("Could not open directory.");
    }

    while (false !== ($file = readdir($handle))) {
        if (substr($file, 0, 1) != '.'){
            print $file . "\n";
        }
    }
    closedir($handle);
}

我收到以下错误:

PHP Warning:  opendir(): Unable to open ssh2.sftp://Resource id #5/outgoing on remote host

这是完全合理的,因为这就是将资源转换为字符串时会发生的情况.文档有错吗?我尝试用主机、用户名和主机替换资源,但也没有用.我知道路径是正确的,因为我可以从命令行运行 SFTP 并且工作正常.

This makes perfect sense because that's what happens when you cast a resource to string. Is the documentation wrong? I tried replacing the resource with host, username, and host and that didn't work either. I know the path is correct because I can run SFTP from the command line and it works fine.

有没有其他人尝试将 SSH2 扩展与 SFTP 一起使用?我在这里遗漏了一些明显的东西吗?

Has anyone else tried to use the SSH2 extenstion with SFTP? Am I missing something obvious here?

更新:

我在内部的另一台机器上设置了 sftp,它工作得很好.因此,我尝试连接的服务器肯定有问题.

I setup sftp on another machine in-house and it works just fine. So, there must be something about the server I am trying to connect to that isn't working.

推荐答案

当连接到 SFTP 服务器并且您需要连接到根文件夹(例如读取文件夹的内容)时,您仍然会收到错误消息仅使用/"作为路径.

When connecting to a SFTP server and you need to connect to the root folder (for instance for reading the content of the folder) you would still get the error when using just "/" as the path.

我找到的解决方案是使用路径/./",这是引用根文件夹的有效路径.当您登录的用户只能访问其自己的根文件夹并且没有可用的完整路径时,这很有用.

The solution that I found was to use the path "/./", that's a valid path that references to the root folder. This is useful when the user you are logging with has access only to its own root folder and no full path is available.

所以尝试读取根文件夹内容时对服务器的请求应该是这样的:

So the request to the server when trying to read the contents of the root folder should be something like this:

$rd = "ssh2.sftp://{$this->sftp}/./";

这篇关于无法让 SFTP 在 PHP 中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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