0

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?

Chris Ullyott
  • 303
  • 1
  • 12

1 Answers1

0

You could try glob: http://php.net/manual/en/function.glob.php. Easy to use and it's fast.

Hans Dubois
  • 269
  • 1
  • 7