Home > front end >  Function to search a specific file in directories and subdirectories PHP
Function to search a specific file in directories and subdirectories PHP

Time:06-29

I need to create a function to search a specific file in all directories and subdirectories, myFile can be anywhere, here is my code :

    $rootDir = realpath($_SERVER["DOCUMENT_ROOT"]) . '/file';
    $filename = 'myFile';

    public function searchFile($rootDir, $filename)
    {
        $dir = opendir($rootDir);

        while ($entry = readdir($dir)) {
            if (is_file("$rootDir/$entry") && $entry == $filename) {
                return "$rootDir/$entry/$filename";
            }
            if (is_dir("$rootDir/$entry")) {
                return $this->searchFile("$rootDir/$entry", $filename);
            }
        }
    }

My problem is that I might have other files than 'myFile' in subdirectories and my recursive function throw me an error because '$entry' is becoming a file.

Here is an example of my directories:

-directory_1
             -directory11
                         -randomFile.pdf
-directory_2
            -myfile
-directory_3
            -directory_33
-etc...

CodePudding user response:

first get list of directories by using

<?php

$dirs = array_filter(glob('*'), 'is_dir');
//print_r($dirs);
?>

and check for file name by using for loop in each folder

<?php foreach($dirs as $key) { ?>

\\your code as you required. 

<? } ?>

To check list of files in directory refer this php function click

CodePudding user response:

Hey you can use PHP Class for this operation

RecursiveDirectoryIterator

RecursiveIteratorIterator

You can find with easy what you want file. Note: My base directory have "a" sub folder has "b" sub folder has "c" and this have test.txt file. –

<?php

$directory = new \RecursiveDirectoryIterator('a');
$iterator = new \RecursiveIteratorIterator($directory);

$filename = 'test.txt';

foreach ($iterator as $info) {
  if ($info->getFilename() == $filename) {
    echo $info->getFileInfo() . "\r\n";
  }
}

// Result
// a/b/c/test.txt

?>
  • Related