← Back to Chapters

PHP glob() Function

? PHP glob() Function

? Quick Overview

The glob() function in PHP is used to search for files matching a specific pattern. It provides an easy way to locate files or directories using wildcard-based patterns similar to shell commands.

? Key Concepts

  • Pattern-based file searching
  • Wildcard support (*, ?)
  • Returns array of matches or false
  • Optional flags for advanced control

? Syntax & Theory

Function Signature:

? View Code Example
// glob function syntax
glob(string $pattern, int $flags = 0): array|false
  • $pattern defines what files to search for.
  • $flags control how matching works.

? Code Example

Finding all .txt files in a directory:

? View Code Example
// Search and display all .txt files
<?php
$directory = "./";
$files = glob($directory . "*.txt");

if ($files) {
echo "Found the following .txt files:<br>";
foreach ($files as $file) {
echo $file . "<br>";
}
} else {
echo "No .txt files found.";
}
?>

? Live Output / Explanation

If matching files exist, each filename is printed. If none exist, a message is shown indicating no matches were found.

? Interactive Concept

Think of glob() as a smart filter that scans a folder and picks only files that match your rule, like selecting all images or scripts automatically.

? Use Cases

  • Loading multiple configuration files
  • Batch processing files
  • Finding specific file types
  • Directory scanning utilities

✅ Tips & Best Practices

  • Always verify the returned value before looping
  • Use GLOB_ONLYDIR to fetch directories
  • Combine with file functions for automation

? Try It Yourself

  • Search for .php or .jpg files
  • Use GLOB_ONLYDIR to list folders
  • Experiment with wildcard patterns
  • Combine multiple extensions using GLOB_BRACE