tags:

views:

338

answers:

3

http://php.net/glob

The documentation page on glob() has this example:

<?php
foreach (glob("*.txt") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
?>

But to be honest, I don't understand how this can work.

The array produced by glob("*.txt") will be traversed, but where does this array come from? Is glob() reading a directory? I don't see that anywhere in the code. Glob() looks for all matches to *.txt

But where do you set where the glob() function should look for these strings?

A: 

Yes, glob reads the directory. Therefore, if you are looking to match files in a specific directory, then the argument you supply to glob() should be specific enough to point out the directory (ie "/my/dir/*.png"). Otherwise, I believe that it will search for files in the 'current' directory.

Note that on some systems filenames can be case-sensitive so "*.png" may not find files ending in ".PNG".

A general overview of its purpose can be found here. Its functionality in PHP is based on that of the libc glob function whose rationale can be read at http://web.archive.org/web/20071219090708/http://www.isc.org/sources/devel/func/glob.txt .

thomasrutter
+2  A: 

Without any directory specified glob() would act on the current working directory (often the same directory as the script, but not always).

To make it more useful, use a full path such as glob("/var/log/*.log"). Admittedly the PHP documentation doesn't make the behaviour clear, but glob() is a C library function, which is where it originates from.

MattJ
+1  A: 

Something useful I've discovered with glob(), if you want to traverse a directory, for example, for images, but want to match more than one file extension, examine this code.

 $images = glob($imagesDir . '*' . '.{jpg,jpeg,png,gif}', GLOB_BRACE);

The GLOB_BRACE flag makes the braces sort of work like the (a|b) regex.

One small caveat is that you need to list them out, so you can't use regex syntax such as jpe?g to match jpg or jpeg.

alex