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?
You could use a RecursiveDirectoryIterator from the SPL library:
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:Saves a lot of work of having to figure out all the files and directories yourself.