Home  >  Article  >  Backend Development  >  How to Find Files in Subfolders with PHP: `glob()` vs. `RecursiveDirectoryIterator`?

How to Find Files in Subfolders with PHP: `glob()` vs. `RecursiveDirectoryIterator`?

Susan Sarandon
Susan SarandonOriginal
2024-11-08 21:07:02464browse

How to Find Files in Subfolders with PHP: `glob()` vs. `RecursiveDirectoryIterator`?

How to Search for Files in Subfolders Using PHP glob()

To search for files in subfolders using PHP's glob() function, consider the following approaches:

Recursive Search with glob()

Utilize the glob() function with recursive traversal:

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:

$result = rglob($_SERVER['DOCUMENT_ROOT'] . '/test.zip');

Recursive Iteration with RecursiveDirectoryIterator

Alternatively, employ RecursiveDirectoryIterator with regular expression matching:

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:

$result = rsearch($_SERVER['DOCUMENT_ROOT'], '/.*\/test\.zip/');

Note that RecursiveDirectoryIterator is available in PHP5, while glob() has been present since PHP4. Both methods effectively search for files within subdirectories.

The above is the detailed content of How to Find Files in Subfolders with PHP: `glob()` vs. `RecursiveDirectoryIterator`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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