Example 1 — List All .txt Files in a Folder
Create a temporary folder with a few files, then use glob() to pick out only the text files.
<?php
$dir = sys_get_temp_dir() . '/glob_demo';
mkdir($dir);
foreach (['b.txt', 'a.txt', 'c.php'] as $name) {
file_put_contents($dir . '/' . $name, 'x');
}
foreach (glob($dir . '/*.txt') as $file) {
echo basename($file), PHP_EOL;
}
array_map('unlink', glob($dir . '/*'));
rmdir($dir); How It Works
- A temporary folder is created and three small files are placed in it.
- The pattern *. txt matches any file name that ends with .txt, so c.php is skipped.
- glob() returns full paths sorted alphabetically, so a. txt comes before b.txt.
- basename() trims each path to the file name, and the cleanup code removes the files and the folder.

