PHP Snippet 1:
$file_to_search = "abc.pdf";
search_file('.',$file_to_search);
function search_file($dir,$file_to_search){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if($file_to_search == $value){
echo "file found<br>";
echo $path;
break;
}
} else if($value != "." && $value != "..") {
search_file($path, $file_to_search);
}
}
}
PHP Snippet 2:
class Test
{
public static function find($dir, $targetFile)
{
$filePath = null;
// pass function ref &$search so we can make recursive call
// pass &$filePath ref so we can get rid of it as class param
$search = function ($dir, $targetFile) use (&$search, &$filePath) {
if (null !== $filePath) return; // early termination
$files = scandir($dir);
foreach ($files as $key => $file) {
if ($file == "." || $file == "..") continue;
$path = realpath($dir . DIRECTORY_SEPARATOR . $file);
if (is_file($path)) {
if ($file === $targetFile) {
$filePath = $path;
break;
}
} else {
$search($path, $targetFile);
}
}
};
$search($dir, $targetFile); // invoke the function
return $filePath;
}
}
// $dir = './', $targetFile = "Foo.php";
echo Test::find($dir, $targetFile);