PHP readdir Function: Reading Directory Entries

Provides a detailed explanation of PHP's readdir function, including its signature, parameters, return values, and example code demonstrating correct and incorrect ways to iterate through directory entries using a directory handle opened by opendir().

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

Function signature: string readdir(resource $dir_handle) Returns the next filename from the directory handle opened by opendir(). Filenames are returned in the order they appear in the filesystem. On failure, the function returns FALSE.

Parameter $dir_handle – a directory handle resource previously obtained via opendir().

Return value

On success, the filename string.

On failure, FALSE.

Example (correct usage)

<?php
// Note: before 4.0.0-RC2 the !== operator does not exist
$handle = opendir('/path/to/files');
echo "Directory handle: $handle
";
echo "Files:
";
/* This is the correct way to iterate a directory */
while (false !== ($file = readdir($handle))) {
    echo "$file
";
}
closedir($handle);
?>

Example (incorrect usage)

<?php
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.

backend-developmentPHPreaddir
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.