How to Use PHP glob Function to Find File Paths

This article explains the purpose, functionality, and practical use cases of the PHP glob() function, a built-in tool designed for finding file paths. You will learn how glob() simplifies directory scanning through pattern matching, how it compares to alternative PHP functions, and how to implement it in your projects with clear, real-world examples.

What is the PHP glob() Function?

The primary purpose of the glob() function in PHP is to search for pathnames that match a specific pattern. It operates based on the rules used by common shells (like the libc globbing rules), allowing you to find files and directories using wildcard characters rather than scanning an entire directory and manually filtering the results.

Unlike functions like scandir(), which return every file and folder within a directory, glob() returns an array of only the filenames or paths that match your criteria. If no matches are found, it returns an empty array, and if an error occurs, it returns false.

How the glob() Syntax Works

The syntax for the glob() function is straightforward:

glob(string $pattern, int $flags = 0): array|false

Common Wildcards Used in Patterns

Useful Flags for glob()

You can customize the output of glob() by passing one or more of the following flags as the second argument:

Practical Examples of glob() in Action

1. Finding All Files of a Specific Extension

If you want to find all .php files in your current working directory:

$files = glob("*.php");
print_r($files);

2. Searching in Specific Subdirectories

To find all .jpg and .png images inside an uploads directory, you can combine the pattern with the GLOB_BRACE flag:

$images = glob("uploads/*.{jpg,png}", GLOB_BRACE);
print_r($images);

3. Finding Only Directories

If you only want to retrieve the paths of folders (and ignore files) inside a directory:

$directories = glob("projects/*", GLOB_ONLYDIR);
print_r($directories);

Why Choose glob() Over Other Directory Functions?

While PHP offers other directory traversal methods like scandir(), readdir(), or the object-oriented DirectoryIterator, glob() is often the preferred choice because of its simplicity and built-in filtering capabilities.

Using scandir() requires you to loop through the results and use helper functions or regular expressions to filter out Unix directory pointers (. and ..) or specific file extensions. glob() handles this filtering natively in a single line of code, reducing CPU overhead and making your codebase cleaner and easier to maintain.