Backend Development 2 min read

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\n";
    echo "Files:\n";
    /* Correct way to iterate the directory */
    while (false !== ($file = readdir($handle))) {
        echo "$file\n";
    }
    /* Incorrect way to iterate the directory */
    while ($file = readdir($handle)) {
        echo "$file\n";
    }
    closedir($handle);
}
?>
BackendFilesystemreaddirdirectory
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

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