English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

Usage and Examples of PHP readdir() Function

PHP Directory Reference Manual

The readdir() function reads entries from a directory handle

Syntax

Syntax

string readdir ( resource $dir_handle );

Definition and Usage

It returns the filename of the next file in the directory. File names are returned in the order stored in the file system.

ParameterSerial Number
1

Parameters and Description

dir_handle(Required)

The resource of the directory handle, previously opened by opendir()

Return Value

Successfully returns the filename, fails to return FALSE.

filename: mohd.gif

Note: This function may return a boolean FALSE, but it may also return a non-boolean value equivalent to FALSE. Please read the Boolean Type section for more information. The === operator should be used to test the return value of this function.

Please pay attention to the style of checking the return value of readdir() in the following example. Here, it is explicitly tested whether the return value is strictly equal to FALSE (value and type are the same - for more information, see comparison operators). Otherwise, any directory item whose name evaluates to FALSE will cause the loop to stop (for example, a directory named "0").
   Example/$dir = opendir("/var/www
   images");
      while (($file = readdir($dir)) !== false) { /echo "filename: " . $file . "<br"
   }
   >";
?>

closedir($dir);

Output Result
filename: .
filename: ..
filename: logo.gif

filename: mohd.gif

Online Example

List all files in the directory :

Please pay attention to the style of checking the return value of readdir() in the following example. Here, it is explicitly tested whether the return value is strictly equal to FALSE (value and type are the same - for more information, see comparison operators). Otherwise, any directory item whose name evaluates to FALSE will cause the loop to stop (for example, a directory named "0").
// <?php 4Note in-.0.02 RC
The not equal operator does not exist before/if ($handle = opendir('/path/to
    echo "Directory handle: $handle\n";
    echo "Files:\n";
    /* This is the correct way to traverse a directory */
    while (false !== ($file = readdir($handle))) {
        echo "\n$file";
    }
    /* This is a wrong way to traverse a directory */
    while ($file = readdir($handle)) {
        echo "\n$file";
    }
    closedir($handle);
}
?>

PHP Directory Reference Manual