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:
Simple example
To find all the files in the directory /path/to/directory with a .txt file extension, you can do this:
The $files array contains the following from the example directory:
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:
print_r($files) would echo:
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.
0 comments:
Post a Comment