Glob was introduced into the PHP function lineup around the time PHP version 4 was released. It's not a new function in the slightest, but like checkdnsrr() it is a fairly undiscovered function for many.
The catchy misnomer that has long been used as a Unix library function, has a similar syntax reminiscent to regular expressions without the expressive power. It allows you to bring back filenames, and also directories, using a straightforward notation.
The Syntax
PHP Code:
foreach(glob('myDirectory/*.php') as $szFilename)
{
echo 'Filename: ' . $szFilename . '<br />';
}
The tiny bit of code above shows the immense power of glob when it comes to harvesting the names of files, and optionally, directories too, from a specified directory - in our case, myDirectory. It will return every file that is contained within myDirectory and that ends with .php. So for instance, index.php would be brought back, but default.asp would not because it ends in .asp.
As you can see, you can place glob straight into a foreach loop where the filename for each single file that matches the notation will be stored as a string in the user variable, $szFilename. This can be echoed straight out or used in conjunction with other functions, for example, filesize(). The string that is returned by the glob function will always be relative to your script based on the notation you are passing to glob.
Optional Flags
You may use the 2nd argument to make glob perform in many different and equally wonderful ways. To give a working example of this, you can use GLOB_BRACE to bring back 2 types of files like I have done in the following example:
PHP Code:
$aFiles = glob('{myDirectory/*.jpg,myDirectory/*.gif}', GLOB_BRACE);
PHP.net defines the following constants to be used as the optional 2nd argument:
- GLOB_MARK - Adds a slash to each item returned
- GLOB_NOSORT - Return files as they appear in the directory (no sorting)
- GLOB_NOCHECK - Return the search pattern if no files matching it 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.
Conclusion
...And that about brings us to a pleasant conclusion on glob! The next time you're perplexed on how to obtain all the files from a directory, or the directories themselves using GLOB_ONLYDIR. Glob is your man! Or woman. Or how about a nice generic "it"?
One thing I am sure about is that glob has too much of a conspicuous name to be placed in a corner and forgotten about. It DEMANDS attention! Much like your girlfriend at half 10 on a Saturday night when you're trying to watch Match Of The Day.


Join the friendly bunch on IRC...