PHP Directories Processing All Files in a Directory Recursively - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Directories Processing All Files in a Directory Recursively - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, July 15, 2019

PHP Directories Processing All Files in a Directory Recursively

PHP Directories


Processing All Files in a Directory Recursively

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.

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. This example counts the total size of files under a directory:

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

Discussion

The objects that the RecursiveDirectoryIterator spits out (and therefore that the RecursiveIteratorIterator passes along) are the same as what you get from DirectoryIterator.

No comments:

Post a Comment

Post Top Ad