2012-11-20 43 views
2

我想從FTP服務器上列出文件。我想獲得子目錄和文件的數組在其中爲一棵樹,如下圖所示:從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); 

隨着文件夾的上面只列出並沒有文件的範例。有關如何解決這個問題的好主意的人? 謝謝。

+0

當你將其否決請讓我知道why.I我堅持,我需要一個更好的援助。有沒有更好的方法呢?謝謝 –

回答

6

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; 
} 
?> 
+0

好極了!它對我很好。非常感謝。你剛剛向我介紹遞歸! –

+0

很高興我能幫忙,遞歸是編程中一個非常重要的概念。 :) – Maccath

+0

不適用於我,如果我把'。'或$ path字段中的'/',它只是連續循環。需要從登錄目錄中獲取所有內容,這有可能嗎? – David

1
function remotedirectory($directory) 
{ 
    global $ftp; 
    $basedir = "/public_html"; 
    $files = ftp_nlist($ftp,$basedir.$directory); 
    foreach($files as $key => $file) 
    { 
     if(is_dir("ftp://username:[email protected]/".$basedir.$directory."/".$file)) 
     { 
      $arrfile[] = remotedirectory($directory."/".$file); 
     }else{ 
      $arrfile[] = $directory.'/'.$file; 
     } 
    } 
    return $arrfile; 
} 
+0

這個方法的任何缺點('is_dir')?我發現這比使用沒有點的目錄名稱更可靠,而且比重複的'ftp_chdir'更穩定,用於目錄檢查,這會在一段時間後靜默超時。 – berliner