PHP readdir() Function
Definition
The readdir() function returns the name of the next entry in a directory.
Syntax
PHP readdir() Function has the following syntax.
readdir(dir_handle);
Parameter
Parameter | Is Required | Description |
---|---|---|
dir_handle | Optional. | Directory handle resource previously opened with opendir(). If this parameter is not specified, the last link opened by opendir() is assumed |
Return
PHP readdir() Function returns the entry name (filename) on success. FALSE on failure.
Example
readdir() function takes the handle returned from opendir().
Each time you call readdir(), it returns the filename of the next file in the directory.
Once it reaches the end of the directory, it will return false.
Here is an example of how to list the contents of a directory:
<?PHP/* w w w. j ava 2s .c o m*/
$handle = opendir('/path/');
if ($handle) {
while (false !== ($file = readdir($handle))) {
print "$file \n";
}
closedir($handle);
}
?>
The code above generates the following result.
Example 2
Open a directory, read its contents, then close:
<?php//w w w .j a v a 2s .c o m
$dir = "/images/";
// Open a directory, and read its contents
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "\n";
}
closedir($dh);
}
}
?>