ShareThis

Monday, November 26, 2012

[PHP] Loop through files in directory and subdirectories

PHP has a lot of great functionality in its standard library. One helpful functionality is the RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator, which allows you to easily recurse over files in a folder structure (including sub-folders!).

First, create an instance of the RecursiveDirectoryIterator,with the parameter set to the path of your base directory you are inspecting.

Then, using a foreach loop,  use RecursiveIteratorIterator to inspect each file and do whatever logic you would like to on them.

Code:
<?php
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
} 
?> 
Not satisfied? You can find some alternatives to looping directories on StackOverflow.

2 comments:

One more blog to lesezeichen, ill end up being keeping tabs on this

Thanks , this was just what I needed

Post a Comment