PHP glob() Function

Usage — The PHP glob() function is used to find all the pathnames matching a specific pattern. In other words, you can use it to get all the filenames and directories that match a given pattern.

It has the following syntax:

PHP

array glob ( string $pattern [, int $flags = 0 ] )

Here is an example of using glob():

PHP

/* Output —
Array
(
    [0] => date.txt
    [1] => email.txt
    [3] => food.txt
    [4] => poem.txt
    [5] => stats.txt
) */
print_r(glob("*.txt"));

Return Value — This function returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.

Additional Information — Keep in mind that on some systems it is impossible to distinguish between empty match and an error.

PHP Version and Changelog — The glob() function is available in PHP 4 >= 4.3.0, PHP 5, PHP 7. The GLOB_ERR flag was added to this function in PHP 5.1.0.

Relevant Functions — Other related PHP functions that you should know about are: opendir() which opens a directory handle, readdir() which reada an entry from directory handle, closedir() which closes a directory handle and fnmatch() which matches a filename against a pattern.

Go Directly To — usage, parameters, working examples or additional tips.

Parameters

pattern

The pattern parameter is used to specify the pattern. No tilde expansion or parameter substitution is done. This is a required parameter.

flags

The flags parameter is used to specify special settings. This is an optional parameter. It can have any of the following values:

  • GLOB_MARK - This flag adds a slash to each directory returned.
  • GLOB_NOSORT - This flag returns files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically.
  • GLOB_NOCHECK - This flag returns the search pattern if no files matching it were found.
  • GLOB_NOESCAPE - Backslashes do not quote metacharacters
  • GLOB_BRACE - With this flag, the function expands {a,b,c} to match ‘a’, ‘b’, or ‘c’.
  • GLOB_ONLYDIR - This flag returns only directory entries which match the pattern.
  • GLOB_ERR - This flag tells the function to stop on read errors like unreadable directories etc. All these errors are ignored by default.

Working Examples

Here are some examples of using the glob() function:

PHP

/* Output —
Citizen.jpg size 970320
Village_panorama.jpg size 223607
profile.jpg size 379432
download.jpg size 269777 */

foreach (glob("*.jpg") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

Additional Tips

Here are some of the most upvoted tips taken from the comment section of the PHP manual:

  1. You should remember that glob() uses two special symbols that act like sort of a blend between a meta-character and a quantifier. These two characters are the * and ?. The ? matches 1 of any character except a /. Similarly, the * matches 0 or more of any character except a /.

    Also keep in mind that the regex for glob() also supports character classes and negative character classes, using the syntax [] and [^]. It will match any one character inside [] or match any one character that is not in [^].

    Let’s say you have a list of files named: ‘x.txt’, ‘xx.txt’, ‘xy.txt’, ‘xyz.txt’, ‘y.txt’, ‘yz.txt’ and ‘yza.txt’.

    • If you used glob("[xy]*.txt), you will get all the files all the files that start with either ‘x’ or ‘y’. In other words, the above glob() will match all our files because they all start with either ‘x’ or ‘y’.

    • If you used glob("[xy].txt"), you will only get the files x.txt and y.txt. This is because [] is only supposed to match a single character.

    • If you used glob("[^x]*.txt"), you will get all the files that don’t start with ‘x’.

    • If you used glob("[^xy]*.txt"), you will get nothing because all the files start with either ‘x’ or ‘y’. However, according to the pattern, they are neither supposed to start with ‘x’ nor with ‘y’.

    You can also use ranges of characters inside the character class by having a starting and ending character with a hyphen in between. For example, [a-z] will match any letter between a and z, [0-9] will match any (one) number, etc..

    One more thing that I would like to point out is that glob() also supports limited alternation with {n1, n2, etc..}. However, you will have to specify GLOB_BRACE as the 2nd argument for glob() in order for it to work. Now if you executed glob("{x,y,z}.txt", GLOB_BRACE), you will match three files named ‘x.txt’, ‘y.txt’ and ‘z.txt’. A more interesting example would be glob("al{ex,isha}.txt", GLOB_BRACE) which will get all files named ‘alex.tx’ or ‘alisha.txt’.

    Suggested by - crayonviolent at phpfreaks dot com

  2. Here is a recursive version of glob(). Keep in mind that it does not support the flag GLOB_BRACE.

    PHP

    if ( ! function_exists('glob_recursive')) {
        function glob_recursive($pattern, $flags = 0) {
            $files = glob($pattern, $flags);
            foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
                $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
            }
        return $files;
        }
    }
    

    Suggested by - Mike

Further Reading

  1. You can read more about the PHP glob() function on PHP.net.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top