Glob: Recursive Folder Scanning for Specific Files
You have a server with multiple folders and files, and you're looking to create a search functionality that provides a download link for a specified file. The current script effectively searches for the file in the root folder, but you need it to scan deeper into subfolders as well.
Recursive Search with glob
One approach to achieve recursive search is by utilizing the glob() function with a customized recursive search function, rglob:
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; }
Example Usage:
$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/test.zip'); // To find "test.zip" recursively $result = rglob($_SERVER['DOCUMENT_ROOT'] . '/*test.zip'); // To find all files ending with "test.zip"
Alternative: RecursiveDirectoryIterator
Another option is to use RecursiveDirectoryIterator:
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; }
Example Usage:
$result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*\/test\.zip/')); // To find "test.zip" recursively
Both RecursiveDirectoryIterator and glob can accomplish the recursive search task, and the choice between them depends on your PHP version and preference.
The above is the detailed content of How to Perform Recursive Folder Scanning for Specific Files in PHP?. For more information, please follow other related articles on the PHP Chinese website!