Using 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.
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:
- Get the directory name and filename from a full path name with PHP (Thursday, December 10th 2009)
- Using PHP's scandir() function to find files in a directory (Friday, July 17th 2009)
- Reading through a directory with PHP (Thursday, June 18th 2009)
- Get the included files with PHP (Thursday, June 4th 2009)
- Create a file with a unique name with PHP (Thursday, February 28th 2008)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
