PHP Directory readdir() Function (With Examples)

In this tutorial, we will learn about the PHP readdir() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP readdir() function

The full form of readdir is "Read Directory", the function readdir() is used to read the directory i.e. read the name of the next entry in the directory.

Syntax

The syntax of the readdir() function:

readdir(dir_handle);

Parameters

The parameters of the readdir() function:

  • dir_handle – it is an optional parameter which is used to specify the directory handle resource if we do not specify the directory handle resource – it assumes the last link opened with opendir() function.

Return Value

If the function execution is success – it returns the filename if the function execution is failed – it returns "FALSE".

PHP readdir() Function Example

PHP code to open a directory, read its files, and close it.

<?php

$path = "/home";

//checking whether $path is a directory or not
//then, opening the directory and reading its files
if (is_dir($path)) {
    if ($dh = readdir($path)) {
        while (($file = readdir($dh)) !== false) {
            echo "File:" . $file . "<br/>";
        }
        //closing the directory
        readdir($dh);
    }
}
?>

Output

The output of the above example is:

File:..
File:main.php
File:.

Reference: PHP readdir() function

To understand the above example, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.