PHP glob://

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.

Using glob() Function

The standard glob() function searches for files matching a pattern ?

<?php
foreach (glob("test/*.php") as $filename) {
    echo "$filename size " . filesize($filename) . "<br>";
}
?>
test/index.php size 1024
test/config.php size 512

Using glob:// Stream Wrapper

The glob:// stream wrapper works with DirectoryIterator for more advanced file handling ?

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

Pattern Matching Examples

Using wildcards and character classes for flexible pattern matching ?

<?php
// Match files starting with 'test'
$files1 = glob("test*");

// Match files with single character between 'file' and '.txt'
$files2 = glob("file?.txt");

// Match files with specific extensions
$files3 = glob("*.{jpg,png,gif}", GLOB_BRACE);
?>

Conclusion

The glob:// stream wrapper provides an object-oriented approach to pattern matching, while glob() offers a simple functional interface. Both are useful for file system operations requiring pattern-based file selection.

Updated on: 2026-03-15T09:26:58+05:30

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements