PHP glob://

PHPServer Side ProgrammingProgramming

Introduction

The glob:// stream wrapper is available in all PHP versions after 5.3.0. It finds pathnames that match given pattern. Similar purpose is fulfilled by PHP's filesystem function glob() which follows libc glob() rules.

Parameters

Special characters

  • * − Matches zero or more characters.
  • ? − Matches exactly one character (any character).
  • [...] − Matches one character from a group of characters. If the first character is !, matches any character not in the group.
  • \ − Escapes the following character, except when the GLOB_NOESCAPE flag is used.

Valid flags

  • GLOB_MARK − Adds a slash (a backslash on Windows) to each directory returned
  • GLOB_NOSORT − Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically
  • 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.

Examples

Using glob() function

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

Using glob:// stream wrapper

<?php
$it = new DirectoryIterator("glob://test/*.php");
foreach($it as $f) {
   echo "File name: " . $f->getFilename() . " size: " . $f->getSize() . "\n";);
}
?>

Both scripts display name and size of files with .php extension in test subdirectory

raja
Published on 22-Sep-2020 14:12:23
Advertisements