通过 SFTP 的远程服务器中文件和文件夹的完整列表 [英] Complete list of files and folders in remote server via SFTP

查看:40
本文介绍了通过 SFTP 的远程服务器中文件和文件夹的完整列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 中如何通过 SFTP 递归列出远程服务器中的所有文件?

How to list all files recursively in remote server via SFTP in PHP?

opendirscandir 仅列出当前文件夹.

opendir or scandir only list in current folder.

推荐答案

phpseclib library 已构建递归列表-in,只需使用 Net_SFTP.nlist() with $recursive = true:

phpseclib library has recursive listing built-in, just use Net_SFTP.nlist() with $recursive = true:

set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
require_once("Net/SFTP.php");

$sftp = new Net_SFTP($hostname);

if (!$sftp->login($username, $password))
{
    die("Cannot login to the server");
}

if (!($files = $sftp->nlist($path, true)))
{
    die("Cannot read directory contents");
}

foreach ($files as $file)
{
    echo "$file\n";
}


如果您甚至需要列出文件夹名称(以便您捕获甚至空文件夹),您必须重新实现,nlist 所做的:

function nlist_with_folders($sftp, $dir)
{
    $files = $sftp->rawlist($dir);
    if ($files === false)
    {
        $result = false;
    }
    else
    {
        $result = array();
        foreach ($files as $name => $attrs)
        {
            if (($name != ".") && ($name != ".."))
            {
                $path = "$dir/$name";
                $result[] = $path;
                if ($attrs["type"] == NET_SFTP_TYPE_DIRECTORY)
                {
                    $sub_files = nlist_with_folders($sftp, $path);
                    $result = array_merge($result, $sub_files);
                }
            }
        }
    }

    return $result;
}


以下关于 phpseclib 1.0 分支的说法是正确的,其 2020 年的最新版本 1.0.19 仍然可用,但似乎不再更新.phpseclib 2.0 和 3.0 使用 Composer,所以它们的设置有些复杂.


The following was/is true about phpseclib 1.0 branch, whose latest release 1.0.19 from 2020 is still usable, but it does not seem to be updated anymore. The phpseclib 2.0 and 3.0 use Composer, so their setup is somewhat more complicated.

phpseclib 不需要任何安装,也没有任何强制依赖项.这是一个纯 PHP" 代码.您只需下载带有 PHP 代码的存档并将其解压缩到您的网络服务器(或在本地解压缩并上传提取的代码,如果您没有对网络服务器的 shell 访问权限).在我的示例中,我已将其解压缩到 phpseclib 子文件夹.

phpseclib does not require any installation and does not have any mandatory dependencies. It's a "pure PHP" code. You just download an archive with the PHP code and extract it to your webserver (or extract it locally and upload the extracted code, if you do not have a shell access to the webserver). In my example, I have extracted it to phpseclib subfolder.

这篇关于通过 SFTP 的远程服务器中文件和文件夹的完整列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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