Backend Development 2 min read

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

Example (incorrect usage)

<?php
while ($file = readdir($handle)) {
    echo "$file\n";
}
closedir($handle);
?>
backend developmentphpfilesystemreaddirdirectory handling
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.