The glob Function
The glob
function searches for files and directories matching a given pattern.
The first parameter is a string with the search pattern.
The second optional parameter specifies flags to modify the function's behavior.
Syntax
glob(pattern, [flags]);
Flags
Flag | Description |
---|---|
GLOB_MARK |
Adds a slash / to each returned directory. |
GLOB_NOSORT |
Returns files in the order they appear in the directory (without sorting). |
GLOB_NOCHECK |
Returns the search pattern if no matches are found. |
GLOB_NOESCAPE |
Backslashes do not escape metacharacters. |
GLOB_BRACE |
Expands {a,b,c} to search for multiple patterns. |
GLOB_ONLYDIR |
Returns only directories matching the pattern. |
GLOB_ERR |
Stop on read errors (e.g., permission denied). |
Example
Find all files with the .txt
extension in the current directory:
<?php
$res = glob('*.txt');
print_r($res);
?>
Code execution result:
['file1.txt', 'file2.txt', 'notes.txt']
Example
Find all files starting with 'test'
with any extension:
<?php
$res = glob('test*');
print_r($res);
?>
Code execution result:
['test.php', 'test.txt', 'test_image.jpg']
Example
Using the GLOB_BRACE
flag to search by multiple patterns:
<?php
$res = glob('*.{php,txt}', GLOB_BRACE);
print_r($res);
?>
Code execution result:
['index.php', 'config.php', 'readme.txt']
Example
Searching for files in subdirectories using the GLOB_RECURSE
flag:
<?php
$res = glob('**/*.php', GLOB_BRACE|GLOB_RECURSE);
print_r($res);
?>
Code execution result:
['index.php', 'lib/utils.php', 'admin/index.php']
See Also
-
the
scandir
function,
which reads the contents of a directory -
the
file_exists
function,
which checks for the existence of a file -
the
is_file
function,
which checks if a file is a regular file