PHP Directory - read() Method
The PHP Directory::read() method 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.
This method is same as readdir() function, only dir_handle defaults to $this->handle.
Syntax
public Directory::read()
Parameters
No parameter is required.
Return Value
Returns the entry name on success or false on failure.
Note: This method 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 method.
Example: List all entries in a directory
The example below shows the usage of Directory::read() method.
<?php $dir = "/temp/images"; //opens the directory, and read its contents if (is_dir($dir)){ if ($d = dir($dir)){ //reading all entry from directory handle while (($file = $d->read()) !== false){ echo "File Name: ".$file."\n"; } //closing the directory handle $d->close(); } } ?>
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 ($d = dir($dir)){ //reading all entry from directory handle while (($file = $d->read()) !== false){ if ($file != "." && $file != "..") { echo "File Name: ".$file."\n"; } } //closing the directory handle $d->close(); } } ?>
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 Date and Time Reference