In this guide, we will discuss the usage, and syntax of the readdir() function of PHP with examples.
What is a readdir() Function in PHP?
The readdir() function in PHP is designed to read the contents of a directory. It takes a directory handle as its parameter, which is obtained by opening the directory using the opendir() function. The readdir() function then retrieves the next entry (file or directory) from the specified directory.
Syntax
The basic format for using the readdir() function in PHP is as follows:
The readdir() function of PHP accepts only one optional parameter, dir_handle. It specifies the directory that is previously opened or handled using the opendir() function. It returns the file name of the next file from your directory on the successful execution, else returns False.
Example of readdir() Function PHP
The following example explains the usage of the readdir() function of PHP.
In this code, we have assigned the path to open the directory in PHP to the dir_handle variable. We then used the while loop to display the list of the content of the files directory. Within the while loop, the readdir() function is used to read the content. On each iteration, it moves the pointer to the next file and displays the name of that file. The closedir() function is used to close the previously opened directory.
Note: The . and .. in the above output refer to the current and parent directories respectively.
You can skip . and .. to appear in the output using a while statement, and the updated code after doing the process is given below:
// opening a directory
$dir_handle = opendir("files");
// reading the contents of the directory
while (($file_name = readdir($dir_handle)) !== false) {
// Skip entries "." and ".."
if ($file_name != "." && $file_name != "..") {
echo "File Name: " . $file_name;
echo "<br>";
}
}
// closing the directory
closedir($dir_handle);
?>
Bottom Line
In PHP, the readdir() function is used to get the list of the files of the given directory. This function accepts only one parameter, dir_handle that is used in the opendir() function to open the specific directory. By using the readdir() function in PHP, you can iterate over the files and directories in the file, perform actions on them and filter the required files.