Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP list all files in directory [duplicate]

Possible Duplicate:
Get the hierarchy of a directory with PHP
Getting the names of all files in a directory with PHP

I have seen functions to list all file in a directory but how can I list all the files in sub-directories too, so it returns an array like?

$files = files("foldername"); 

So $files is something similar to

array("file.jpg", "blah.word", "name.fileext") 
like image 564
Mark Lalor Avatar asked Sep 30 '10 00:09

Mark Lalor


2 Answers

foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.')) as $filename) {     // filter out "." and ".."     if ($filename->isDir()) continue;      echo "$filename\n"; } 


PHP documentation:

  • RecursiveDirectoryIterator
  • RecursiveIteratorIterator
like image 83
Matthew Avatar answered Sep 18 '22 15:09

Matthew


So you're looking for a recursive directory listing?

function directoryToArray($directory, $recursive) {     $array_items = array();     if ($handle = opendir($directory)) {         while (false !== ($file = readdir($handle))) {             if ($file != "." && $file != "..") {                 if (is_dir($directory. "/" . $file)) {                     if($recursive) {                         $array_items = array_merge($array_items, directoryToArray($directory. "/" . $file, $recursive));                     }                     $file = $directory . "/" . $file;                     $array_items[] = preg_replace("/\/\//si", "/", $file);                 } else {                     $file = $directory . "/" . $file;                     $array_items[] = preg_replace("/\/\//si", "/", $file);                 }             }         }         closedir($handle);     }     return $array_items; } 
like image 26
Ruel Avatar answered Sep 18 '22 15:09

Ruel