Consider these two folder structures:
Foo/
Folder1/
File1.txt
Folder2/
Folder3/
File2.txt
Bar/
Folder1/
Folder2/
Folder3/
Folder4/
I'd like to know the most efficient way in PHP to tell me that the "Foo" folder has two files in it and that the "Bar" folder has zero files in it. Notice that it's recursive. Even though the "File1.txt" file is not immediately inside the "Foo" folder, I still want it to count. Also, I don't care what the names of the files are. I just want the total number of files.
Any help would be appreciated. Thanks!
Use RecursiveDirectoryIterator
. Here is the documentation.
$rdi = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/home/thrustmaster/Temp', FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($rdi as $file)
echo "$file
";
print iterator_count($rdi);
You need a recursive function to loop through the directory structure. That's all you can really do to count the number of files without going with object orientated solution.
This function will recursively count the number of files in a directory and it's sub-directories.
function countDir($dir, $i = 0) {
if ($handle = opendir($dir.'/')) {
while (false !== ($file = readdir($handle))) {
// Check for hidden files the array[0] on a
// string returns the first character
if ($file[0] != '.') {
if (is_dir($dir.'/'.$file)) {
$i += countDir($dir.$file, $i);
} else {
$i++;
}
}
}
}
return $i;
}