views:

815

answers:

3

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
    }
};

Can you help, plz?

+3  A: 

Come on, first try it yourself! ;)

What you'll need:

scandir()
is_dir

and of course foreach

http://de.php.net/manual/de/function.is-dir.php

http://de3.php.net/manual/de/function.scandir.php

Psaniko
+3  A: 

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($file) && $file != '.' && $file != '..'){
       readDirs($file);
    }
    else{
      //do stuff
    }
  } 
}

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

GSto
It will fall in infinite loop trying to recursively read directory "." (single dot - current directory). You need to modify your if-statement: if (is_dir($file) and $file != '.')
Michał Rudnicki
thanks, I forgot about that, added it to the code. Glad I put that untested disclaimer :)
GSto
thank you both :)
NetCaster
missing closing parenthesis `while($file = readdir($dirHandle){`, otherwise works perfect! Thanks.
Matt
+6  A: 

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/>';
}
Michał Rudnicki
+1 for using SPL :)
Inspire