php glob - scan in subfolders for a file

php glob - scan in subfolders for a file

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

php glob - scan in subfolders for a file

The glob() function is a convenient utility for finding files, but it behaves differently than you might expect when dealing with nested directory structures. In your current implementation, the pattern $root/*/test.zip specifically targets directories directly within $root. It effectively expands to paths like /var/www/html/subfolder1/test.zip, but it completely ignores anything buried deeper in the hierarchy. This limitation stems from how glob patterns work: they do not recurse by default.

To scan sub-folders and sub-sub-folders, you need to enable recursion explicitly. The solution is straightforward: append a trailing slash to your search pattern. Changing $root/*/test.zip to $root/**/test.zip tells glob() to traverse the entire directory tree beneath $root.

Here is how you can update your code to handle deep nesting:

$root = $_SERVER['DOCUMENT_ROOT'];
$search = "test.zip";
// The double asterisk enables recursive searching through all subdirectories
$found_files = glob("$root/**/$search");

if (!empty($found_files)) {
    // Return the first match found. Be aware that order is not guaranteed.
    $firstMatch = $found_files[0];
    $downloadlink = str_replace($root . "/", "", $firstMatch);

    echo "<a href=\"http://www.example.com/$downloadlink\">$search</a>";
} else {
    // Handle the case where no files are found to prevent undefined index notices
    echo "File '$search' not found.";
}

Understanding Pattern Expansion

The core mechanic here is the expansion of the ** wildcard. A single asterisk (*) matches any sequence of characters within a single directory level, whereas a double asterisk (**) instructs the underlying C function to descend into subdirectories at every depth level. This behavior aligns with how many filesystem utilities operate, such as the find command in Linux, which also uses recursive logic when given specific flags or patterns.

Handling Multiple Matches and Ordering

When you enable recursion, one significant side effect is that glob() returns an array of all matches, sorted alphabetically. If a user has placed test.zip in both /var/www/html/ and /var/www/html/uploads/archives/test.zip, the function will return both paths. Your current logic assumes exactly one result exists. In a real-world scenario where files are duplicated across the server, relying on $found_files[0] might lead to returning a file from an unintended location, such as a staging environment or a backup directory.

If you strictly require the "most specific" path (the deepest one) or the first one found by filesystem order, you must sort the results or filter them before selecting the index. Alternatively, if performance is a concern on a massive server with thousands of matching files, iterating through an entire array just to pick one might be inefficient.

Security and Path Validation

Before constructing your download link, it is critical to validate that the resulting path is actually within your intended $root directory. Recursive searches can sometimes behave unexpectedly if symbolic links are involved. If a subdirectory contains a symlink pointing outside of $root, glob() will follow that link and potentially return a path located in an insecure location on the server.

You should sanitize the output to ensure it doesn't escape your domain root:

$cleanPath = str_replace($root . "/", "", $firstMatch);

// Ensure the decoded path doesn't start with ../ or contain unexpected segments
if (!str_starts_with($cleanPath, '..') && !preg_match('/\.\./', $cleanPath)) {
    // Proceed with echo
} else {
    // Reject the file as it might be outside the intended scope
}

Performance Considerations

Scanning a large directory tree is an I/O intensive operation. The time complexity increases with the number of files and the depth of the filesystem. If your server hosts millions of files, glob() with recursion can cause noticeable latency. In high-traffic applications or when scanning very deep structures, consider using the find command via a shell execution if you need more granular control over the search (e.g., limiting to specific file types or excluding certain folders), although executing shell commands from PHP requires careful sanitization of inputs to prevent security vulnerabilities.

For most standard use cases involving a moderate number of files, the double-asterisk approach provides the necessary balance between ease of use and performance without needing external dependencies.

Our network