Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Use scandir($path) to get an array of names from one directory, glob() to match a pattern such as *.php, and PHP’s SPL iterators to process entries as objects or walk a directory tree. For manual, incremental reading, pair opendir() with readdir().
Choose the right PHP directory-listing method
| What you need | Use | What to know |
|---|---|---|
| An array of entries in one directory | scandir() |
Includes files and directories; sorts alphabetically by default. |
| Names or paths matching a pattern | glob() |
Returns matching pathnames; use flags to change sorting or pattern behavior. |
| Object-oriented iteration over one directory | DirectoryIterator or FilesystemIterator |
Provides entry objects and access to file information. |
| Entries throughout a directory tree | RecursiveDirectoryIterator with RecursiveIteratorIterator |
Set the starting directory and decide which descendants to include. |
| Manual, incremental reading | opendir() and readdir() |
Yields entries in filesystem order, not guaranteed alphabetical order. |
List the contents of one directory with scandir()
scandir() is the straightforward choice when you want an array of entry names. The PHP manual describes it as returning “an array of files and directories from the directory.” It includes both kinds of entries, as well as the special . and .. entries, so skip those if they are not useful to your application.
As an Amazon Associate I earn from qualifying purchases.
$path = __DIR__ . '/uploads';
$entries = scandir($path);
if ($entries === false) {
throw new RuntimeException('Could not scan directory');
}
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
echo $entry, PHP_EOL;
}
By default, scandir() returns names in ascending alphabetical order. Pass SCANDIR_SORT_DESCENDING for descending order or SCANDIR_SORT_NONE when you do not want sorting. If the path is not a directory, the function returns false and emits an E_WARNING; check the result before iterating. To include only files or only directories, join each name to the directory path and test it with is_file() or is_dir().
Recommended Free Tools
List files matching a pattern with glob()
Use glob() when the selection is naturally expressed as a filename pattern. For example, this lists matching JPG paths in an uploads directory:
#1 Best Overall
$matches = glob(__DIR__ . '/uploads/*.jpg');
if ($matches === false) {
throw new RuntimeException('Pattern lookup failed');
}
foreach ($matches as $path) {
echo $path, PHP_EOL;
}
The result is an array of matching pathnames, an empty array when nothing matches, or false on error. Results are sorted alphanumerically unless you pass GLOB_NOSORT. The supported shell-like patterns include *, ?, and character classes; brace alternatives require GLOB_BRACE. glob() does not expand a tilde or perform parameter substitution. It searches files accessible through the server’s filesystem, so it is not a way to list remote files.
Iterate one directory with DirectoryIterator
Choose DirectoryIterator when an object-oriented loop and entry methods are more convenient than an array of names. Its isDot() method identifies . and .., while getFilename() returns the current entry’s name.
Rank #2
$directory = new DirectoryIterator(__DIR__ . '/uploads');
foreach ($directory as $item) {
if ($item->isDot()) {
continue;
}
echo $item->getFilename(), PHP_EOL;
}
FilesystemIterator is another one-directory option. It builds on the SPL iterator interfaces and lets you choose flags that affect how the current value and key are represented.
List files recursively with SPL iterators
To visit descendants as well as entries in the starting directory, combine RecursiveDirectoryIterator with RecursiveIteratorIterator. This example skips dot entries and prints files only:
$directory = new RecursiveDirectoryIterator(
__DIR__ . '/uploads',
FilesystemIterator::SKIP_DOTS
);
$iterator = new RecursiveIteratorIterator($directory);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isFile()) {
echo $fileInfo->getPathname(), PHP_EOL;
}
}
The recursive directory iterator supplies entries and recursion support; the recursive iterator walks the descendants. The isFile() condition is what limits this example’s output to files. Remove or adjust that check if you also need directories, and use a recursive filter when only certain names or subtrees belong in the results. Keep the starting directory as narrow as the task requires. The FilesystemIterator::FOLLOW_SYMLINKS flag changes whether symbolic links are followed, so enable it only when that traversal behavior is intended.
The iterator constructor throws UnexpectedValueException when the directory does not exist. Passing an empty string throws ValueError in PHP 8 and later; PHP 8.0 changed this from the earlier RuntimeException behavior.
Rank #4
Read entries incrementally with opendir() and readdir()
Use the procedural pair when you need explicit control over the directory handle or want to process each entry as it is read, rather than first collecting an array.
$handle = opendir(__DIR__ . '/uploads');
if ($handle === false) {
throw new RuntimeException('Could not open directory');
}
try {
while (($entry = readdir($handle)) !== false) {
if ($entry === '.' || $entry === '..') {
continue;
}
echo $entry, PHP_EOL;
}
} finally {
closedir($handle);
}
readdir() returns names in the order stored by the filesystem, which is not guaranteed to be alphabetical. Sort the names yourself if display order matters. Compare its result strictly with false: a loose false-like check can mistake a valid entry for the end of the listing. Pass the directory handle explicitly; using null for the handle has been deprecated since PHP 8.5.0. The finally block closes the handle even if processing throws an exception.
Handle failures and PHP-version differences
Check the return or exception behavior of the API you choose, and verify the PHP version deployed by your application. scandir() and glob() can return false; their failures should be handled before a loop assumes an array. The iterator constructor reports a missing directory with UnexpectedValueException, while an empty path has the PHP 8.0 behavior described above. For manual reading, check whether opendir() returned false, compare readdir() strictly with false, and close an opened handle.
For most single-directory listings, start with scandir(). Switch to glob() when the pattern defines the selection, SPL iterators when object access or recursion is useful, and the procedural pair when incremental handle control is the priority.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minute




