PHP glob() Function
The PHP glob() function returns an array of filenames or directories matching a specified pattern. The function returns an array containing the matched files/directories or an empty array if no match is found. It returns false on error.
Syntax
glob(pattern, flags)
Parameters
pattern |
Required. Specify the pattern to search for. In the pattern, no tilde expansion or parameter substitution is done. The following special characters can be used:
|
flags |
Optional. Specify flag for special setting. Possible values are:
|
Return Value
Returns an array containing the matched files/directories, an empty array if no file matched or false on error.
Example: glob() example
In the example below, glob() function is used to get the filenames of all text files in the current working directory.
<?php //displaying all text files print_r(glob('*.txt')); ?>
The output of the above code will be:
Array ( [0] => error.txt [1] => input.txt [2] => test.txt )
Example: getting size of all files
Consider the example below, where this function is used to return the size of all files present in the current working directory.
<?php //getting file size of all file present //in current working directory foreach (glob("*.*") as $filename) { echo "$filename, size: ".filesize($filename)."\n"; } ?>
The output of the above code will be:
Main.php, size: 100 error.txt, size: 0 input.txt, size: 0 test.txt, size: 48
❮ PHP Filesystem Reference