PHP readdir() Function: Reading Directory Entries

The PHP readdir() function reads the next entry from an opened directory handle, returning the filename in filesystem order, with details on its parameters, return values, and example code demonstrating correct and incorrect directory traversal techniques.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP readdir() Function: Reading Directory Entries

The PHP readdir() function reads the next entry from an opened directory handle and returns the filename in the filesystem's sorting order.

Parameters dir_handle – a resource representing the directory handle opened previously by opendir().

Return value

Returns the filename as a string on success, or FALSE on failure.

Example

<?php
// Note: the !== operator does not exist before version 4.0.0‑RC2
if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle
";
    echo "Files:
";
    /* Correct way to iterate the directory */
    while (false !== ($file = readdir($handle))) {
        echo "$file
";
    }
    /* Incorrect way to iterate the directory */
    while ($file = readdir($handle)) {
        echo "$file
";
    }
    closedir($handle);
}
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPFilesystemreaddirdirectory
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.