search for in the  
<fwriteis_dir>
Last updated: Thu, 19 May 2005

glob

(PHP 4 >= 4.3.0, PHP 5)

glob -- Find pathnames matching a pattern

Description

array glob ( string pattern [, int flags] )

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells. No tilde expansion or parameter substitution is done.

Returns an array containing the matched files/directories or FALSE on error.

Valid flags:

  • 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

Note: Before PHP 4.3.3 GLOB_ONLYDIR was not available on Windows and other systems not using the GNU C library.

Example 1. Convenient way how glob() can replace opendir() and friends.

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

Output will look something like:

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

Note: This function will not work on remote files as the file to be examined must be accessible via the servers filesystem.

See also opendir(), readdir(), closedir(), and fnmatch().



User Contributed Notes
glob
Michael T. McGrew
16-May-2005 09:12
Take all file names in the directory and put them in a link.
<?php
foreach (glob("*.*") as $filename)
{
   echo
"<a href=\"".$filename."\">".$filename."</a><br/>";
}
?>
cgamedude at yahoo dot com
05-May-2005 05:38
Here is the *correct* way to do a reverse-alphabetical search:
<?
$Results
= glob( 'blah.*' );
rsort( $Results );
?>
There now, wasn't that easy? :)
Deviant
04-Apr-2005 06:53
A slight edit on the globr() function stated by sthomas. This does exactly the same just works on windows systems for < PHP 4.3.3. :

<?php

function globr($sDir, $sPattern, $nFlags = NULL) {
  
$aFiles = glob("$sDir/$sPattern", $nFlags);
  
$files = getDir($sDir);
   if (
is_array($files)) {
       foreach(
$files as $file ) {
          
$aSubFiles = globr($file, $sPattern, $nFlags);
          
$aFiles = array_merge($aFiles,$aSubFiles);
       }
   }
   return
$aFiles;
}

function
getDir($sDir) {
  
$i=0;
   if(
is_dir($sDir)) {
       if(
$rContents = opendir($sDir)) {
           while(
$sNode = readdir($rContents)) {
               if(
is_dir($sDir.'/'.$sNode )) {
                   if(
$sNode !="." && $sNode !="..") {
                      
$aDirs[$i] = $sDir.'/'.$sNode ;
                      
$i++;
                   }
               }
           }
       }
   }
   return
$aDirs;
}

?>
cjcommunications at gmail dot com
01-Apr-2005 07:02
Here is a way I used glob() to browse a directory, pull the file name out, resort according to the most recent date and format it using date(). I called the function inside a <select> and had it go directly to the PDF file:

function browsepdf(){
   $pdffile=glob("printable/*.pdf");
   rsort($pdffile);
   foreach($pdffile as $filename){
       $filename=ltrim($filename, "printable/");
       $filename=rtrim($filename, ".pdf");
       $file=$filename;
       $datetime=strtotime($filename);
       $newdate=strtotime("+3 days",$datetime);
       $filenamedate=date("F d", $datetime);
       $filenamedate.=" - ".date("F d, Y", $newdate);
       echo "<option value='$file'>$filenamedate</option>";
   }
}
fraggy(AT)chello.nl
23-Mar-2005 05:23
glob caused me some real pain in the buttom on windows, because of the DOS thing with paths (backslashes instead of slashes)...

This was my own fault because I "forgot" that the backslash, when used in strings, needs to be escaped, but well, it can cause a lot of confusion, even for people who are not exactly newbies anymore...

For some reason, I didn't have this problem with other file operations (chdir, opendir, etc...), which was the most confusing of all...

So, for people running scripts on Windows machines (Dos95, 98 or WinNT or DosXP), just remember this:

glob('c:\temp\*.*'); // works correctly, returns an array with files.
glob("c:\temp\*.*"); // does NOT work... the backslashes need to be escaped...
glob("c:\\temp\\*.*"); // that works again...

This is especially confusing when temporary writable directories are returned as an unescaped string.

$tempdir = getenv('TEMP');
// this returns "C:\DOCUME~1\user\LOCALS~1\Temp"
so in order to scan that directoy I need to do:

glob($tempdir . "\\*.*");

Or perhaps it's easier to replace all backslashes with slashes in order to avoid these kinds of confusions...

glob("c:/temp/*.*"); // works fine too...

I know I'm not contributing anything new here, but I just hope this post may avoid some unnecessary headaches...
NOSPAM sketch at infinite dot net dot au
14-Mar-2005 07:05
in the example below, i found i got an error if the directory was empty.

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

I think its because glob()'ing an empty directory returns false, and so calling foreach (false as $value) will obviously break.

to fix this, i did the following:
<?php
$files
= glob("*.txt) or array(); // give it an empty array if the directory is empty or glob fails otherwise
   echo "
$filename size " . filesize($filename) . "\n";
}
?>

Hope this helps someone
29-Jan-2005 04:09
Be aware...

On Windows you need to add "/" mark:
<?php
$files
= glob("/dir/*.txt"); // Works properly.
$files = glob("dir/*.txt"); // Failure!, first letter is missing on every filename!
?>

On Unix you cant add the "/" mark:
<?php
$files
= glob("dir/*.txt"); // Works properly.
$files = glob("/dir/*.txt"); // No files found!
?>

Hope this will save your time :)
23-Jan-2005 03:54
The example on this page will generate a warning if the glob function does not find any filenames that match the pattern.

The glob function result will only be an array if it finds some files and the foreach statement requires its argument to be an array.

By checking for the possibility that the result of the glob function may not be an array you can eliminate the warning.

Here's a better example:

<?php
$matches
= glob("*.txt");
if (
is_array ( $matches ) ) {
   foreach (
$matches as $filename) {
      echo "$filename size " . filesize($filename) . "\n";
   }
}
?>
Paul Gregg / Qube #efnet
30-Mar-2004 07:52
Just threw this together in response to a common question in irc:

Available at: http://www.pgregg.com/projects/
http://www.pgregg.com/projects/php/code/preg_find.phps

preg_find() - A function to search in a directory for files or directories matching a preg_ pattern.  Tell it the pattern, the start directory and some optional flags and it will return an array of files and their associated stat() details.  If you just want the filenames, just do an array_keys() on the result.

e.g. $files = preg_find("/\.php$/", '.', PREG_FIND_RECURSIVE);
will find all files ending in .php in the current directory and below.

Options are:
// PREG_FIND_RECURSIVE  - go into subdirectorys looking for more files
// PREG_FIND_DIRMATCH  - return directorys that match the pattern also
// PREG_FIND_FULLPATH  - search for the pattern in the full path (dir+file)
// PREG_FIND_NEGATE    - return files that don't match the pattern
// to use more than one simple seperate them with a | character

Hope you find it useful.

Paul.
Per Lundberg
25-Nov-2003 09:57
Be aware that on UNIX, * as the pattern will *not* match dot-files and dot-directories.  Knowing this will save you some headache.  :-)  May He bless you.
MichaelSoft
06-Nov-2003 05:28
Note that, in some configurations, the search is case-sensitive! You'll need to have something like:

<?php
$images
= glob("/path/to/images/{*.jpg,*.JPG}", GLOB_BRACE);
?>

Also on some servers, I have seen such scripts 'crash' with an CGI Error ("...not returning a complete set of HTTP headers...") when glob could not find any match!
ryan at wonko dot com
30-Oct-2003 01:03
Here's an example of how to use the GLOB_BRACE flag:

<?php
$images
= glob("/path/to/images/{*.gif,*.jpg,*.png}", GLOB_BRACE);
?>

It's also worth noting that when using the GLOB_BRACE flag in any version of PHP prior to 4.3.4, PHP will crash if no matches are found.
sthomas at townnews dot com
11-Mar-2003 05:41
<?php
/**
 * Recursive version of glob
 *
 * @return array containing all pattern-matched files.
 *
 * @param string $sDir      Directory to start with.
 * @param string $sPattern  Pattern to glob for.
 * @param int $nFlags      Flags sent to glob.
 */
function globr($sDir, $sPattern, $nFlags = NULL)
{
 
$sDir = escapeshellcmd($sDir);

 
// Get the list of all matching files currently in the
  // directory.

 
$aFiles = glob("$sDir/$sPattern", $nFlags);

 
// Then get a list of all directories in this directory, and
  // run ourselves on the resulting array.  This is the
  // recursion step, which will not execute if there are no
  // directories.

 
foreach (glob("$sDir/*", GLOB_ONLYDIR) as $sSubDir)
  {
  
$aSubFiles = rglob($sSubDir, $sPattern, $nFlags);
  
$aFiles = array_merge($aFiles, $aSubFiles);
  }

 
// The array we return contains the files we found, and the
  // files all of our children found.

 
return $aFiles;
}

?>
martin dot rode at zeroscale dot com
19-Feb-2003 01:37
If you don't have PHP >= 4.3 available and don't want to hassle with PHP (:-) do something like this on GNU/Linux:

<?php
foreach (explode("\n",`find -type d -maxdepth 1 ! -name ".*" -printf "%f\n" `) as $dirname) {
   print
$dirname;
}
?>

With the "find" you can "glob" whatever you like.
tmm at aon dot at
21-Dec-2002 06:50
I have written my own function for searching files, but it only supports ? and *
However it should be easily expandable.

<?php
// e.g. $matches=GetMachingFiles(GetContents("."),"*.txt");
function GetMatchingFiles($files, $search) {

  
// Split to name and filetype
  
if(strpos($search,".")) {
    
$baseexp=substr($search,0,strpos($search,"."));
    
$typeexp=substr($search,strpos($search,".")+1,strlen($search));
   } else {
    
$baseexp=$search;
    
$typeexp="";
   }
    
  
// Escape all regexp Characters
  
$baseexp=preg_quote($baseexp);
  
$typeexp=preg_quote($typeexp);
    
  
// Allow ? and *
  
$baseexp=str_replace(array("\*","\?"), array(".*","."), $baseexp);
  
$typeexp=str_replace(array("\*","\?"), array(".*","."), $typeexp);
      
  
// Search for Matches
  
$i=0;
   foreach(
$files as $file) {
    
$filename=basename($file);
      
     if(
strpos($filename,".")) {
      
$base=substr($filename,0,strpos($filename,"."));
      
$type=substr($filename,strpos($filename,".")+1,strlen($filename));
     } else {
      
$base=$filename;
      
$type="";
     }

     if(
preg_match("/^".$baseexp."$/i",$base) && preg_match("/^".$typeexp."$/i",$type))  {
      
$matches[$i]=$file;
      
$i++;
     }
   }
   return
$matches;
}

And if
someone's searching for a function which gets all files from a directory including the subdirectories:

// Returns all Files contained in given dir, including subdirs
function GetContents($dir,$files=array()) {
  if(!($res=opendir($dir))) exit("$dir doesn'
t exist!");
  while((
$file=readdir($res))==TRUE)
   if(
$file!="." && $file!="..")
     if(is_dir("
$dir/$file")) $files=GetContents("$dir/$file",$files);
       else array_push(
$files,"$dir/$file");
    
  closedir(
$res);
  return
$files;
}

?>
leon at leonatkinson dot com
17-Oct-2002 08:03
Since this function is a wrapper for the OS function of the same name, you may find it helpful to look at the man page while the exact PHP implementation is sorted out.

You might have some luck passing in the literal values of the constants defined in /usr/include/glob.h.  For example, GLOB_NOSORT is defined as (1 << 2), which is 4.  In PHP, glob('*.php', 4) will returns an unsorted list for me in RH 7.x.  YMMV.
opessin at ifrance dot com
07-Jul-2002 05:48
If this function is not available in your version of PHP, think looking at the 'Directory Functions' which can be used instead.
http://www.php.net/manual/en/ref.dir.php

<fwriteis_dir>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT