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
}
};
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 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 ' Found File or .-dir '.$item.'<br>'; } } } $path = "/"; echo "$path<br>"; readDirs($path);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With