2011-12-19 36 views
0

如何列出目錄中的所有文件。我只想要根目錄中的文件。如果根目錄中有任何目錄,我想跳過它們中的那些目錄和文件。
現在使用此代碼如何使用php列出目錄中的文件

$folderPath = file_directory_path().'/lexalytics/'; 
    if ($handle = opendir($folderPath)) { 
     $result .= '<div><ul>'; 
     while (false !== ($entry = readdir($handle))) { 
      if ($entry != "." && $entry != "..") { 
       $result .= "<li><a href=../".$folderPath.$entry.">".$entry."</a>\n</li>"; 
      } 
     } 
     $result .= '</ul></div>'; 
     closedir($handle); 
    } 

但它列出了它們的子目錄和文件。 如何避免這些?請幫助我

+0

在原有的功能有遞歸查找的選項。只是不要進行遞歸搜索。 – Bakudan 2011-12-19 09:36:06

+0

這不是PHP5。 – Flukey 2011-12-19 14:11:29

回答

0

試試這個代碼

$folderPath = file_directory_path().'/lexalytics/'; 
    $handle = @opendir($folderPath) or die("Unable to open $path"); 
    $result .= '<div><ul>'; 
    // Loop through the files 
    while ($entry = @readdir($handle)) { 
     if(is_file($folderPath.$entry)) { 
      $result .= "<li><a href=../".$folderPath.$entry.">".$entry."</a>\n</li>"; 
     } 
    } 
    $result .= '</ul></div>'; 
    closedir($handle); 
+1

爲什麼你使用'@'符號來抑制函數中的錯誤?你爲什麼使用die而不是拋出異常?糟糕的代碼。 – Flukey 2011-12-19 14:09:54

1
 
$path = "your-path"; 

    // Open the folder 
    $dir_handle = @opendir($path) or die("Unable to open $path"); 

    // Loop through the files 
    while ($file = readdir($dir_handle)) { 

    if($file == "." || $file == ".." || $file == "index.php") 

     continue; 
     echo "<a href=\"$file\">$file</a><br />"; 

    } 
    // Close 
    closedir($dir_handle); 
+0

這也打印子目錄的名稱 – 2011-12-19 09:56:10

3

請使用PHP5s新DirectoryIterator類:

此只列出文件和排除的文件夾:

$directory = file_directory_path().'/lexalytics/'; 
$filenames = array(); 
$iterator = new DirectoryIterator($directory); 
foreach ($iterator as $fileinfo) { 
    if ($fileinfo->isFile()) { 
     $filenames[$fileinfo->getMTime()] = $fileinfo->getFilename(); 
    } 
} 
相關問題