Recursively Scan a Directory Using PHP SPL DirectoryIterator

Recursively scan a Root folder and ALL it’s sub-folders using PHP’s SPL DirectoryIterator class. This example shows how to get all Image Files under a certain folder recursively but can easily be used to get any or all types of files.

The Code

 * Get IMAGE files recursively from Root and all sub-folders
 * Skip folders in our list of results
 * LEAVES_ONLY mode makes sure ONLY FILES/Leafs endpoint is returned
 * Make sure file extension is in our Images extensions array
$path = 'E:\Server\_ImageOptimize\img\testfiles';

$directory = new RecursiveDirectoryIterator($path,RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directory,RecursiveIteratorIterator::LEAVES_ONLY);

$extensions = array("png", "jpg", "jpeg", "gif", "gifgif");

foreach ($iterator as $fileinfo) {
    if (in_array($fileinfo->getExtension(), $extensions)) {
        echo 'File path = ' .$fileinfo->getPathname(). NL;
        echo 'File extension = ' .$fileinfo->getExtension(). NL;
        $files[] = $fileinfo->getPathname();
echo '<pre>';
echo '</pre>';

The Result

    [0] => E:\Server\_ImageOptimize\img\testfiles\css3-generator.png
    [1] => E:\Server\_ImageOptimize\img\testfiles\css3-please.png
    [2] => E:\Server\_ImageOptimize\img\testfiles\css3-tools-10.png
    [3] => E:\Server\_ImageOptimize\img\testfiles\fb.jpg
    [4] => E:\Server\_ImageOptimize\img\testfiles\mysql.gif-or8.png
    [5] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-generator.png
    [6] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-please.png
    [7] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\css3-tools-10.png
    [8] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\fb.jpg
    [9] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\mysql.gif-or8.png
    [10] => E:\Server\_ImageOptimize\img\testfiles\OriginalImages\support-browsers.png
    [11] => E:\Server\_ImageOptimize\img\testfiles\support-browsers.png
    [12] => E:\Server\_ImageOptimize\img\testfiles\testgif.gif

Share our Article...

Subscribe by Email...

November 8 2012

Written by

Web-Developer from Central Florida. This blog is my outlet to what I am into at the time. PHP, Javascript, MySQL, OO Practices, Performance, Cool Software and Services, etc... Please subscribe to the RSS feed

  • Albert Diones

    Hi! Sorry being OC but why call the “Included Extensions” as “$exntensions” ?

    • Jason Davis

      Hello, thanks for spotting that, it is just a typo, I have corrected, thanks

  • Sajjad Ashraf

    Thank you.