Find Files and Folders with Glob() in PHP

Glob() is a very useful PHP function to search for files and folders in PHP. More technically, it returns an array of filenames or directories matching a specified pattern. Below you can a few usage examples:

List all files and folders in a directory:

$path = "/path/to/folder/*";
 
foreach(glob($path) as $file) 
{
    echo "Filename: ".htmlspecialchars($file)." - Filetype: " . filetype($file) . "<br />";
}

Find all *.php files in the current directory:

 print_r(glob("*.php"));

This is the PHP function structure:

 array glob ( string $pattern [, int $flags = 0 ] )

And these are the available flags:

GLOB_MARK - Adds a slash to each directory returned
GLOB_NOSORT - Return files as they appear in the directory (no sorting)
GLOB_NOCHECK - Return the search pattern if no files matching it were found
GLOB_NOESCAPE - Backslashes do not quote meta characters
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

PHP: glob – Manual

More Related Posts