3

我正在尝试列出来自 FTP 服务器的文件。我想得到一组子目录和其中的文件作为树,如下所示:

folder1
       file1.txt
       file2.txt
folder2
       folder2a
               file1.txt
               file2.txt
               file.3txt
       folder2b
              file1.txt

现在我的数组将类似于

[folder1]=>array(file1.txt,file2.txt) 
[folder2]=>array([folder2a]=>array(file1.txt,file2txt,file3.txt)
[folder2b]=>array(file1.txt))

注意:上面的数组可能不是确切的语法,只是为了让我了解我在寻找什么。我尝试了 ftp_nlist() 但似乎只返回文件和文件夹,而不是子文件夹中的文件。这是我的代码外观的示例

 // set up basic connection
$conn_id = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// get contents of the ftp directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

上面它只列出文件夹而不是文件。任何人都知道如何解决这个问题?谢谢你。

4

2 回答 2

7

ftp_nlist()不递归地获取文件和目录,它只返回指定路径的所有文件和文件夹。您可以编写一个函数以递归方式获取结果。这是某人编写的递归函数示例,我在 PHP ftp_nlist()文档中找到:

<?php 
/** 
 * ftpRecursiveFileListing 
 * 
 * Get a recursive listing of all files in all subfolders given an ftp handle and path 
 * 
 * @param resource $ftpConnection  the ftp connection handle 
 * @param string $path  the folder/directory path 
 * @return array $allFiles the list of files in the format: directory => $filename 
 * @author Niklas Berglund 
 * @author Vijay Mahrra 
 */ 
function ftpRecursiveFileListing($ftpConnection, $path) { 
    static $allFiles = array(); 
    $contents = ftp_nlist($ftpConnection, $path); 

    foreach($contents as $currentFile) { 
        // assuming its a folder if there's no dot in the name 
        if (strpos($currentFile, '.') === false) { 
            ftpRecursiveFileListing($ftpConnection, $currentFile); 
        } 
        $allFiles[$path][] = substr($currentFile, strlen($path) + 1); 
    } 
    return $allFiles; 
} 
?>
于 2012-11-20T11:45:21.567 回答
2
function remotedirectory($directory)
{
    global $ftp;
    $basedir = "/public_html";
    $files = ftp_nlist($ftp,$basedir.$directory);
    foreach($files as $key => $file)
    {
        if(is_dir("ftp://username:password@doamin/".$basedir.$directory."/".$file))
        {
            $arrfile[] = remotedirectory($directory."/".$file);
        }else{
            $arrfile[] = $directory.'/'.$file;
        }
    }
    return $arrfile;
}
于 2014-07-29T13:11:21.237 回答