Useing glob() to Find Pathnames

Posted by on May 12, 2010 in PHP | Comments Off

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.

The downside of this function is it will not work on remote files as the file to be examined must be accessible via the server’s filesystem and it isn’t available on some systems (e.g. old Sun OS).

glob()

  array glob  (  string $pattern  [,  int $flags = 0  ] )

Pattern

The pattern. No tilde expansion or parameter substitution is done.

Flags

  • GLOB_MARK – Adds a slash to each directory 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.

Return Values

Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Note: On some systems it is impossible to distinguish between empty match and an error.

Example

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

It works like scandir() function but it is more capable and flexible. It can let you search for files by using patterns.

  $files = glob('*.php'); 
  print_r($files); 
Array 
  ( 
  [0] => phptest.php 
  [1] => pi.php 
  [2] => post_output.php 
  [3] => test.php 
  ) 

And to fetch multiple file types, you should use it like this:

  $files = glob('*.{php,txt}', GLOB_BRACE);
  print_r($files);
  Array 
  ( 
  [0] => phptest.php 
  [1] => pi.php 
  [2] => post_output.php 
  [3] => test.php 
  [4] => log.txt 
  5] => test.txt 
  ) 

Comments are closed.