You want to do something to all the files in a directory and in any subdirectories. For example, you want to see how much disk space is consumed by all the files under a directory.
Use a RecursiveDirectoryIterator and a RecursiveIteratorIterator. The Recur siveDirectoryIterator extends the DirectoryIterator with a getChildren() method that provides access to the elements in a subdirectory.
The RecursiveIteratorIt erator flattens the hierarchy that the RecursiveDirectoryIterator returns into one list.
This example counts the total size of files under a directory:
1 2 3 4 5 6 |
$dir = new RecursiveDirectoryIterator('/usr/local'); $totalSize = 0; foreach (new RecursiveIteratorIterator($dir) as $file) { $totalSize += $file->getSize(); } print "The total size is $totalSize.\n"; |
The objects that the RecursiveDirectoryIterator spits out (and therefore that the RecursiveIteratorIterator passes along) are the same as what you get from DirectoryIterator.