I'm trying to create a function that will efficiently search the document root for a file and return its path. Currently I have the following thanks to the RecursiveDirectoryIterator and RegexIterator.
<?php
function find_file($filename) {
$pattern = preg_quote($filename);
$dir = new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT']);
$iterate = new RecursiveIteratorIterator($dir);
$reg_iterate = new RegexIterator($iterate, "/.*$pattern.*/", RegexIterator::GET_MATCH);
$ignore_pattern = '(\/?)(_*?)(old|archive|backup|cache|node_modules)';
foreach($reg_iterate as $matches){
foreach($matches as $file){
$file = rtrim($file, '.');
if(!preg_match("/$ignore_pattern/i", $file)){
return $file;
}
}
}
}
echo find_file('styles.css');
?>
I'm trying though to ignore certain directories from searching, for performance reasons. I'd rather not be scanning through directories that are known to be fruitless. Currently, I can only ignore certain patterns of paths after receiving the list of files from RecursiveIteratorIterator, so it's slow. Is there a smarter method you might recommend?