Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
};
like image 890
EzzDev Avatar asked Jan 06 '10 16:01

EzzDev


4 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/>'; } 
like image 87
Michał Niedźwiedzki Avatar answered Sep 21 '22 17:09

Michał Niedźwiedzki


You need to add the path to your recursive call.

function readDirs($path){   $dirHandle = opendir($path);   while($item = readdir($dirHandle)) {     $newPath = $path."/".$item;     if(is_dir($newPath) && $item != '.' && $item != '..') {        echo "Found Folder $newPath<br>";        readDirs($newPath);     }     else{       echo '&nbsp;&nbsp;Found File or .-dir '.$item.'<br>';     }   } }  $path =  "/"; echo "$path<br>";  readDirs($path); 
like image 34
John Marty Avatar answered Sep 19 '22 17:09

John Marty


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.

like image 23
GSto Avatar answered Sep 19 '22 17:09

GSto


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.

like image 38
Fedir RYKHTIK Avatar answered Sep 20 '22 17:09

Fedir RYKHTIK