Recipe 24.9. Processing All Files in a Directory Recursively


24.9.1. Problem

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.

24.9.2. Solution

Use a RecursiveDirectoryIterator and a RecursiveIteratorIterator. The RecursiveDirectoryIterator extends the DirectoryIterator with a getChildren( ) method that provides access to the elements in a subdirectory. The RecursiveIteratorIterator flattens the hierarchy that the RecursiveDirectoryIterator returns into one list. Example 24-24 counts the total size of files under a directory.

Processing all files in a directory recursively

<?php $dir = new RecursiveDirectoryIterator('/usr/local'); $totalSize = 0; foreach (new RecursiveIteratorIterator($dir) as $file) {     $totalSize += $file->getSize(); } print "The total size is $totalSize.\n"; ?>

24.9.3. Discussion

The objects that the RecursiveDirectoryIterator spits out (and therefore that the RecursiveIteratorIterator passes along) are the same as what you get from DirectoryIterator, so all the methods mentioned in Table 24-4 are available.

24.9.4. See Also

Documentation on RecursiveDirectoryIterator at http://www.php.net/~helly/php/ext/spl/classRecursiveDirectoryIterator.html and RecursiveIteratorIterator at http://www.php.net/~helly/php/ext/spl/classRecursiveIteratorIterator.html.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net