Using PHP's glob() function to find files in a directoryUsing PHP's glob() function to find files in a directory

Posted July 2nd, 2009 in PHP

A couple of weeks ago I posted how to read through a directory with PHP using the opendir() readdir() and closedir() functions and now look at the glob() function. glob() returns the filenames into an array and supports pattern matching so it can be very easy to find e.g. jpg images in a particular directory.

Get a 7-Day Free Trial to FunPass.

Example directory

The examples below look at a directory with the following, the same example directory as used in the read through directory post:

bar.txt       A regular file
baz           A directory
foo.txt       A regular file
link2foo.txt  A symbolic link to foo.txt

Simple example

To find all the files in the directory /path/to/directory with a .txt file extension, you can do this:

$files = glob("/path/to/directory/*.txt");

The $files array contains the following from the example directory:

Array
(
    [0] => /path/to/directory/bar.txt
    [1] => /path/to/directory/foo.txt
    [2] => /path/to/directory/link2foo.txt
)

If no files matched the pattern then the array will be empty.

Example using braces

There are flags which can be passed as a second optional parameter. One of these is GLOB_BRACE which means that e.g. {jpg,gif,png} will be expanded to match jpg, gif and png which can be useful if you need to look for a particular set of files by their extension, in this example for image files.

If the example directory also had the files 1.jpg, 2.gif and 3.png then you can do this to get glob to return just the image files:

$files = glob("/path/to/directory/*.{jpg,gif,png}", GLOB_BRACE);

print_r($files) would echo:

Array
(
    [0] => /path/to/directory/1.jpg
    [1] => /path/to/directory/2.gif
    [2] => /path/to/directory/3.png
)

Further reading

This serves as an introduction to using glob() to find files with PHP. Read the glob manual page for more details and for information about the other flags.

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus