Recursion through a directory tree in PHP

12,204

Solution 1

The call to is_dir and recurseDirs is not fully correct. Also your counting didn't work correctly. This works for me:

$dir = "/usr/";
function recurseDirs($main, $count=0){
    $dirHandle = opendir($main);
    while($file = readdir($dirHandle)){
        if(is_dir($main.$file."/") && $file != '.' && $file != '..'){
            echo "Directory {$file}: <br />";
            $count = recurseDirs($main.$file."/",$count); // Correct call and fixed counting
        }
        else{
            $count++;
            echo "$count: filename: $file in $main \n<br />";
        }
    }
    return $count;
}
$number_of_files = recurseDirs($dir);

Notice the changed calls to the function above and the new return value of the function.

Solution 2

Check out the new RecursiveDirectoryIterator.

It's still far from perfect as you can't order the search results and other things, but to simply get a list of files, it's fine.

There are simple examples to get you started in the manual like this one:

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), 
RecursiveIteratorIterator::SELF_FIRST);

foreach($objects as $name => $object){
    echo "$name\n";
}

?>

Solution 3

There is an error in the call

recurseDirs($file);

and in

is_dir($file)

you have to give the full path:

recurseDirs($main . '/' .$file, $count);

and

is_dir($main . '/' .$file)

However, like other anwerers, I suggest to use RecursiveDirectoryIteretor.

Share:
12,204
phphelpplz
Author by

phphelpplz

Updated on July 31, 2022

Comments

  • phphelpplz
    phphelpplz almost 2 years

    I have a set of folders that has a depth of at least 4 or 5 levels. I'm looking to recurse through the directory tree as deep as it goes, and iterate over every file. I've gotten the code to go down into the first sets of subdirectories, but no deeper, and I'm not sure why. Any ideas?

    $count = 0;
    $dir = "/Applications/MAMP/htdocs/site.com";
    function recurseDirs($main, $count){
        $dir = "/Applications/MAMP/htdocs/site.com";
        $dirHandle = opendir($main);
        echo "here";
        while($file = readdir($dirHandle)){
            if(is_dir($file) && $file != '.' && $file != '..'){
                echo "isdir";
                recurseDirs($file);
            }
            else{
                $count++;
                echo "$count: filename: $file in $dir/$main \n<br />";
            }
        }
    }
    recurseDirs($dir, $count);