The readdir() function returns the name of the next entry in a directory.
PHP readdir() Function has the following syntax.
readdir(dir_handle);
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 |
PHP readdir() Function returns the entry name (filename) on success. FALSE on failure.
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 ww .j ava 2 s . c om
$handle = opendir('/path/');
if ($handle) {
while (false !== ($file = readdir($handle))) {
print "$file \n";
}
closedir($handle);
}
?>
The code above generates the following result.
Open a directory, read its contents, then close:
<?php/*from w w w . ja v a 2 s .co 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);
}
}
?>
The following code shows how to get directory recursively.
<?php// ww w.ja v a 2 s .c o m
function directorySize($directory) {
$directorySize=0;
// Open the directory and read its contents.
if ($dh = @opendir($directory)) {
// Iterate through each directory entry.
while (($filename = readdir ($dh))) {
// Filter out some of the unwanted directory entries
if ($filename != "." && $filename != "..")
{
// File, so determine size and add to total
if (is_file($directory."/".$filename))
$directorySize += filesize($directory."/".$filename);
// New directory, so initiate recursion
if (is_dir($directory."/".$filename))
$directorySize += directorySize($directory."/".$filename);
}
}
}
@closedir($dh);
return $directorySize;
}
$directory = '/usr/';
$totalSize = round((directory_size($directory) / 1048576), 2);
printf($totalSize);
?>