How to Perform Recursive Folder Scanning for Specific Files in PHP?

DDD
Release: 2024-11-11 09:19:02
Original
964 people have browsed it

How to Perform Recursive Folder Scanning for Specific Files in PHP?

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;
}
Copy after login

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"
Copy after login

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;
}
Copy after login

Example Usage:

$result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*\/test\.zip/')); // To find "test.zip" recursively
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template