PHP readdir() Function
The PHP readdir() function returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem. The stream must have previously been opened by opendir() function.
Syntax
readdir(dir_handle)
Parameters
dir_handle |
Optional. Specify the directory handle resource previously opened with opendir(). If this parameter is not specified, the last link opened by opendir() is assumed. |
Return Value
Returns the entry name on success or false on failure.
Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.
Example: List all entries in a directory
The example below shows the usage of readdir() function.
<?php $dir = "/temp/images"; //opens the directory, and read its contents if (is_dir($dir)){ if ($dh = opendir($dir)){ //reading all entry from directory handle while (($file = readdir($dh)) !== false){ echo "File Name: ".$file."\n"; } //closing the directory handle closedir($dh); } } ?>
The output of the above code will be:
File Name: fig1.png File Name: fig2.png File Name: Photo.jpg File Name: . File Name: .. File Name: error.jpeg
Example: List all entries in a directory and strip out . and ..
The example below demonstrates how to strip out . and .. from the entry name.
<?php $dir = "/temp/images"; //opens the directory, and read its contents if (is_dir($dir)){ if ($dh = opendir($dir)){ //reading all entry from directory handle while (($file = readdir($dh)) !== false){ if ($file != "." && $file != "..") { echo "File Name: ".$file."\n"; } } //closing the directory handle closedir($dh); } } ?>
The output of the above code will be:
File Name: fig1.png File Name: fig2.png File Name: Photo.jpg File Name: error.jpeg
❮ PHP Directory Reference