a php developer weblog

blog Closed!
calin view of the web development world

2005/10/19

glob() - a useful but obscure PHP function

@ 08:35 AM (31 months, 11 days ago)
Did you know this function exists? Well, since 4.3, there's this new PHP function called glob(); useful if one simply needs a list of files from a directory, and eventually apply ereg patterns to file matching. Before one had to either use the dir() class, or the opendir() function; something like this:

<?php
$d = dir("/dir/");
echo "Handle: " . $d->handle . "n";
echo "Path: " . $d->path . "n";
while (false !== ($entry = $d->read())) {
    if (substr($entry, -3) == 'txt') {
        echo $entry .' size '. filesize($entry) ."n";  
    }
}
$d->close();
?>
 
Now it's quite simple:

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