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 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
