Recursive Directory Listing With PHP

15th February 2008 - 1 minute read time

Use the following function to list the contents of one or more nested directories.

function recursive_directory($dirname,$maxdepth=10, $depth=0){
 if ($depth >= $maxdepth) {
  return false;
 }
 $subdirectories = array();
 $files = array();
 if (is_dir($dirname) && is_readable($dirname)) {
  $d = dir($dirname);
  while (false !== ($f = $d->read())) {
   $file = $d->path.'/'.$f;
   // skip . and ..
   if (('.'==$f) || ('..'==$f)) {
    continue;
   };
   if (is_dir($dirname.'/'.$f)) {
    array_push($subdirectories,$dirname.'/'.$f);
   } else {
    array_push($files,$dirname.'/'.$f);
   };
  };
  $d->close();
  foreach ($subdirectories as $subdirectory) {
    $files = array_merge($files, recursive_directory($subdirectory, $maxdepth, $depth+1));
  };
 }
 return $files;
}

Use this in the following way.

$files = recursive_directory('folder');
print_r($files); // print the result...

The maximum depth that the function will travel down is set to 10 as a default. This can be overwritten at runtime.

$files = recursive_directory('folder', 20); // make maximum level 20
print_r($files); // print the result...

Add new comment

The content of this field is kept private and will not be shown publicly.