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.
Function Signature:
// glob function syntax
glob(string $pattern, int $flags = 0): array|false
Finding all .txt files in a directory:
// 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.";
}
?>
If matching files exist, each filename is printed. If none exist, a message is shown indicating no matches were found.
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.
.php or .jpg files