How to Use the PHP glob() Function

09/05/2021

Contents

In this article, you will learn how to use the PHP glob() function.

PHP glob() Function

The glob() function in PHP is used to search for all the pathnames matching a specified pattern according to the rules used by the library function glob() in C.

Syntax:
array glob ( string $pattern [, int $flags = 0 ] )
Parameters:
  • $pattern is the search pattern. Wildcard characters * and ? can be used.
  • $flags is optional, and it can be used to specify additional flags for the search.
Example:
<?php
  $files = glob("*.txt"); 
  foreach($files as $file) {
    echo $file."\n";
  }
?>

This will search for all txt files in the current directory and print their names.

Here are some additional details and tips for using the glob() function:

  • The glob() function returns an array of filenames/directories matching the specified pattern, or an empty array if no files match.
  • The glob() function supports two wildcard characters: “*” matches zero or more characters, and “?” matches exactly one character.
  • The glob() function performs a case-sensitive search unless the GLOB_CASEFOLD flag is set.
  • To search for directories only, use glob(“*/”).
  • To search recursively, you can use a pattern such as glob(“dirname/*/*.txt”) to search for txt files in all subdirectories of “dirname”.
  • The glob() function can be slow for large numbers of files, especially if used with a pattern that matches many files. In such cases, you may consider using scandir() instead.