Scanning Multiple Subfolders in PHP with glob
In PHP, the glob function can be utilized to search for files within a specified directory. However, when searching across multiple subdirectories and sub-subdirectories, additional considerations are necessary.
Recursive Search with glob
One approach is to employ the recursive capabilities of glob. Here's a function that performs a recursive search for the specified file pattern:
function rglob($pattern, $flags = 0) { $files = glob($pattern, $flags); foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) { $files = array_merge( [], ...[$files, rglob($dir . "/" . basename($pattern), $flags)] ); } return $files; }
To use this function, simply provide the root directory and file pattern as arguments:
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/test.zip'); var_dump($result);
Alternative Approach with RecursiveDirectoryIterator
Another option is to use the RecursiveDirectoryIterator class. Here's a function that leverages this class to search recursively for the specified file pattern:
function rsearch($folder, $regPattern) { $dir = new RecursiveDirectoryIterator($folder); $ite = new RecursiveIteratorIterator($dir); $files = new RegexIterator($ite, $regPattern, RegexIterator::GET_MATCH); $fileList = array(); foreach($files as $file) { $fileList = array_merge($fileList, $file); } return $fileList; }
To invoke this function:
$result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*\/test\.zip/')); var_dump($result);
Both glob and RecursiveDirectoryIterator provide viable solutions for recursively searching for files within multiple subdirectories. The choice between them depends on the specific needs of your application.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3