DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

How to List Files and Directories with PHP

Use scandir() for a simple PHP directory listing, glob() for filename patterns, SPL iterators for object-based or recursive traversal, and opendir()/readdir() for incremental control.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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:

$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.

$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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.