PHP Function Reference

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:
  • * - Matches zero or more characters.
  • ? - Matches exactly one character (any character).
  • [...] - Matches one character from a group of characters. If the first character is !, matches any character not in the group.
  • \ - Escapes the following character, except when the GLOB_NOESCAPE flag is used.
flags Optional. Specify flag for special setting. Possible values are:
  • GLOB_MARK - Adds a slash (a backslash on Windows) to each directory returned.
  • GLOB_NOSORT - Return files as they appear in the directory (no sorting).
  • GLOB_NOCHECK - Return the search pattern if no match were found.
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters.
  • GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'.
  • GLOB_ONLYDIR - Return only directory entries which match the pattern.
  • GLOB_ERR - Stop on read errors (like unreadable directories), by default errors are ignored.

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