Using PHP's glob() Function to Search Files and Directories
This article introduces PHP's glob() function, explains its syntax and parameters, and provides multiple code examples demonstrating how to locate files, filter by patterns, search across multiple directories, and retrieve only directories, while noting performance considerations.
PHP is a widely used programming language for developing web applications, and its standard library includes powerful functions such as glob() that simplify file system tasks.
The glob() function searches for file pathnames that match a given pattern, making it easy to locate multiple files or directories.
Syntax:
<code>glob(pattern, flags)</code>Parameters:
pattern : The pattern to match, which can be a directory name, file name, or a filename containing wildcards like * or ?.
flags (optional): Additional options such as searching hidden files or sorting the results.
Example 1: Find all PHP files in a specific directory
<code>$files = glob('/path/to/directory/*.php');</code>This code returns an array of paths and filenames for all PHP files in the specified directory.
Example 2: Find specific files in multiple directories
<code>$dirs = array('/path/to/directory1/', '/path/to/directory2/');
$files = array();
foreach ($dirs as $dir) {
$files = array_merge($files, glob($dir . '*.txt'));
}</code>The script builds an array of two directories, iterates over each with a foreach loop, and uses glob() to collect all .txt files, merging the results with array_merge() .
Example 3: Use wildcards to find multiple file types
<code>$files = glob('/path/to/directory/*.{php,txt}', GLOB_BRACE);</code>This returns an array containing both PHP and TXT files; the GLOB_BRACE flag enables the brace syntax for specifying multiple extensions.
Example 4: Find all directories
<code>$dirs = glob('/path/to/directory/*', GLOB_ONLYDIR);</code>The GLOB_ONLYDIR flag restricts matches to directories, returning an array of all sub‑directories.
Summary
The glob() function is a practical tool for locating files and directories, but be aware that wildcard searches can impact performance on large file sets. Mastering its usage enables more efficient file system operations in PHP projects.
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.