"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Use glob to Search for a Specific File in Subfolders?

How Can I Use glob to Search for a Specific File in Subfolders?

Posted on 2025-03-13
Browse:898

How Can I Use glob to Search for a Specific File in Subfolders?

php glob: Explore Subfolders for a Specific File

Searching a vast array of files scattered across different folders and subfolders can be a daunting task. However, PHP's glob function provides a versatile solution to address this challenge.

Your initial attempt involved using glob to search within the root directory. To extend its reach beyond the root, consider the following two approaches:

1. Recursive glob with rglob function:

The rglob function enhances glob's capabilities by enabling recursive searches. It recursively descends into subdirectories, returning all matching files. For instance:

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;
}

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

2. Recursive Directory Iterator:

The RecursiveDirectoryIterator class is another option for recursive file searching. It provides a more flexible and object-oriented 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;
}

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

Both approaches can effectively scan subfolders for the specified file. Choose the one that best suits your project's requirements and preferences.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3