Question: Method to recursively search for a file in directory and subdirectories doesn't find the file
I wrote a function to find a file in a specific directory and its sub-directories. You can input the filename with or without extension (basename vs. filename). The second argument is the path to search in. The file is found when it is in the given directory, however, it is not found if it is in a sub-directory. I try to make use of the recusrive call of the function to look in the sub-directories. Any ideas what I am missing?
public function findFileInPathRecursive($file_to_find, $path) { if (substr($path, -1) != "/") $path .= "/"; // Add slash at path's end $files = scandir($path); foreach($files as $file) { if (substr($file, 0, 1) == ".") continue; // skip if "." or ".." if (is_dir($path.$file)) { // if "file" is a directory, call self with the new path $new_path = $path.$file; return $this->findFileInPathRecursive($file_to_find, $new_path); } else { if (pathinfo($file)['basename'] == $file_to_find OR pathinfo($file)['filename'] == $file_to_find) { return $path.$file; } } } return false; }
9codings