★ wanayoo — archive 1999 http://fr.php.net/manual/de/function.glob.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<fwriteis_dir>
view the version of this page
Last updated: Mon, 14 Feb 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

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

Beispiel 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

Anmerkung: Diese Funktion kann nicht mit entfernten Dateien arbeiten, da der Zugriff auf die Datei, die bearbeitet werden soll, über das Dateisystem des Servers möglich sein muss.

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



add a note add a note User Contributed Notes
glob
29-Jan-2005 11: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 10: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
31-Mar-2004 03: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 04: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 12: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 08: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
12-Mar-2003 12: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 08: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
22-Dec-2002 01: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
18-Oct-2002 03: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 12: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: Mon, 14 Feb 2005
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Sat Feb 19 05:12:23 2005 CET