Master PHP’s glob() Function: Find Files and Directories Efficiently

This guide explains how PHP's glob() function works, details its syntax and parameters, and provides multiple practical code examples for locating files and directories using patterns, wildcards, and specific flags.

php Courses
php Courses
php Courses
Master PHP’s glob() Function: Find Files and Directories Efficiently

PHP is a widely used programming language, and its standard library includes the powerful glob() function for finding file pathnames that match a given pattern.

Syntax

glob(pattern, flags)

Parameters

pattern

: the pattern to match; it can be a directory name, a file name, or include wildcards such as * and ?. flags (optional): additional options, for example to search hidden files or control sorting.

Example 1: Find all PHP files in a directory

$files = glob('/path/to/directory/*.php');

The code returns an array containing the paths and filenames of every .php file in the specified directory.

Example 2: Find specific files in multiple directories

$dirs = array('/path/to/directory1/', '/path/to/directory2/');
$files = array();
foreach ($dirs as $dir) {
    $files = array_merge($files, glob($dir . '*.txt'));
}

This searches both directories for .txt files and merges the results into a single array.

Example 3: Use brace wildcard to find multiple file types

$files = glob('/path/to/directory/*.{php,txt}', GLOB_BRACE);

The resulting array contains both PHP and TXT files; the GLOB_BRACE flag enables the brace syntax.

Example 4: Find all directories

$dirs = glob('/path/to/directory/*', GLOB_ONLYDIR);

This call returns an array of all sub‑directories; the GLOB_ONLYDIR flag restricts matches to directories.

Conclusion

glob()

is a very practical function for locating files and directories, but remember that wildcard searches can affect performance, especially when scanning large directory trees.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

backendPHPpattern-matchingfile searchglobphp-functions
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.