PHP readdir() Function
In this chapter you will learn:
- Definition for PHP readdir() Function
- Syntax for PHP readdir() Function
- Parameter for PHP readdir() Function
- Return for PHP readdir() Function
- Example - returns the name of the next entry in a directory
- Example - Open a directory, read its contents, then close
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/*from ja v a 2 s . com*/
$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//from j a v a2s . 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);
}
}
?>
Next chapter...
What you will learn in the next chapter:
- Definition for PHP readfile() Function
- Syntax for PHP readfile() Function
- Parameter for PHP readfile() Function
- Return for PHP readfile() Function
- Example - reads a file and writes it to the output buffer
Home » PHP Tutorial » PHP File Functions