tags:

views:

39

answers:

1

Is there a "performant" way in PHP to search for a file through multiple directories?

Lets say I know that the file may be in one of the search paths:

$pathOne, $pathTwo, $pathThree. But now lets imagine, the user (developer who uses the framework) is able to group his stuff in subfolders as well. $pathTwo contains 20 subfolders, and each subfolder contains 2 more subfolders.

How could I search across all these paths plus subfolders for a $file? I've seen some frameworks using the file_exists() function excessively to do something like that (but without searching down the subfolders). Probably I would need a way to figure out which folders are there, and then step into them?

+3  A: 

You could use a RecursiveDirectoryIterator from the SPL library:

$dir_iterator = new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator,
                    RecursiveIteratorIterator::SELF_FIRST);

foreach ($iterator as $file) {
    echo $file, "\n";
}

The above code will print out a list of all the files in the directory you specify, including all subdirectories. You could alter the foreach() loop slightly to perform your file matching logic to find the file you are looking for, like this:

$dir_iterator = new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator,
                    RecursiveIteratorIterator::SELF_FIRST);

foreach ($iterator as $splFile) {
    if ($splFile->getBaseName() == $file) {
        echo "Found it";
        //do stuff
        break;
    }
}

Saves a lot of work of having to figure out all the files and directories yourself.

zombat
You can omit SELF_FIRST when you don't want directories and you could also make the check for the filename into a FilterIterator.
Gordon
please, can you give an example? I can't get that to work that way.
openfrog
@openfrog - The second block of code is a complete working example, and works fine if you just change the "/path" on the first line. What kind of problem are you having?
zombat