How to Recursively Search for Files in Subfolders with PHP: Glob vs. RecursiveDirectoryIterator?

Linda Hamilton
Release: 2024-11-08 21:44:02
Original
865 people have browsed it

How to Recursively Search for Files in Subfolders with PHP: Glob vs. RecursiveDirectoryIterator?

PHP Glob: Recursive Search for Files in Subfolders

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 with Recursion

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

RecursiveDirectoryIterator

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

Comparison and Usage

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template