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 に答える