When scanning a server for files, the need often arises to extend the search beyond the root folder to include subfolders and sub-subfolders. Here's how to achieve this using PHP's glob function and RecursiveDirectoryIterator.
Glob provides a limited form of recursive search with the glob() function. However, it lacks support for certain options like GLOB_BRACE. To overcome this, you can use a custom function rglob() that recursively traverses the directory structure and returns a merged array of matching files:
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; }
Another option for recursive search is the RecursiveDirectoryIterator class. It offers a more robust and extensible approach:
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; }
Both rglob() and rsearch() can perform recursive file searches. RecursiveDirectoryIterator offers additional flexibility through its extensibility options. The choice between the two depends on your specific requirements and desired level of control.
The above is the detailed content of How to Recursively Search for Files in Subfolders with PHP: Glob vs. RecursiveDirectoryIterator?. For more information, please follow other related articles on the PHP Chinese website!