PHP read sub-directories and loop through files how to?

directory, loops, php

Solution

Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.

$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
    echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}

Problem

I need to create a loop through all files in subdirectories. Can you please help me struct my code like this: ``` $main = "MainDirectory"; loop through sub-directories { loop through filels in each sub-directory { do something with each file } }; ```

Original source