PHP read sub-directories and loop through files how to?

Viewed 71183

I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:

$main = "MainDirectory";
loop through sub-directories {
    loop through filels in each sub-directory {
        do something with each file
    }
};
9 Answers

Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.

$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}

You probably want to use a recursive function for this, in case your sub directories have sub-sub directories

$main = "MainDirectory";

function readDirs($main){
  $dirHandle = opendir($main);
  while($file = readdir($dirHandle)){
    if(is_dir($main . $file) && $file != '.' && $file != '..'){
       readDirs($file);
    }
    else{
      //do stuff
    }
  } 
}

didn't test the code, but this should be close to what you want.

I like glob with it's wildcards :

foreach (glob("*/*.txt") as $filename) {
    echo "$filename\n";
}

Details and more complex scenarios.

But if You have a complex folders structure RecursiveDirectoryIterator is definitively the solution.

Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..

function readDirs($path){
  $dirHandle = opendir($path);
  while($item = readdir($dirHandle)) {
    $newPath = $path."/".$item;
    if (($item == '.') || ($item == '..')) {
        continue;
    }
    if (is_dir($newPath)) {
        pretty_echo('Found Folder '.$newPath);
        readDirs($newPath);
    } else {
        pretty_echo('Found File: '.$item);
    }
  }
}

function pretty_echo($text = '')
{
    echo $text;
    if (PHP_OS == 'Linux') {
        echo "\r\n";
    }
    else {
        echo "</br>";
    }
}
Related