php.readdir()
PHP provides a built-in function called readdir()
that allows us to read the contents of a directory and return the existing filenames as an array. The function is very similar to the readdir()
in the C standard library.
In this tutorial, we will explore how we can use the readdir()
function to read and
PHP readdir() Function
The function allow us to read an entry from the directory handle. The function syntax is as shown:
readdir(?resource $dir_handle = null): string|false
The function accepts a single parameter:
dir_handle()
- this represents the directory handle resource opened using theopendir()
function.
The function returns an entry name on success and false
on failure.
Example
The following examples demonstrates how we can use the readdir()
function to perform a series of actions.
Example 1 - List all Entries in a Directory
The following example demonstrates how to use the function to list all the entries in a directory.
$dir_handle = opendir('/home/d3b1an');
if ($dir_handle) {
while (($file = readdir($dir_handle)) !== false) {
echo "$file\n";
}
closedir($dir_handle);
}
The resulting output is as shown:
.bash_history
.profile
.bash_logout
.bashrc
.local
.php_history
info.php
..
.
The code above uses the opendir()
function to open the directory provided in the bath. It then uses the readdir()
function to print the name of each file using the echo command.
Finally, se use the closedir()
function to close the target directory.
Example 2- List all entries in the current directory and strip out .
and ..
To strip the current and previous directory from the output, we can do:
<?php
if ($handle = opendir('/home/d3b1an')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
?>
Resulting output:
.bash_history
.profile
.bash_logout
.bashrc
.local
.php_history
info.php
And there you have it, a way to print the contents of a directory using the readdir()
function.
Conclusion
In this tutorial, you learned the workings of the readdir()
function to gather the listing of all files in a given directory.
Want to learn more about PHP?, check our similar tutorials below.