PHP dir() Function

What is PHP dir() Function?

Use dir() function to create an instance of the directory class. The function provides you a handle of the directory class that you can use to read and rewind content (files and folders) of directory. And you can also close the handle. Actually, the directory class has three methods –

  • read() – To get a list of all the files and folders (not the sub folders) of the directory, use this method.
  • rewind() – To start over the read() method, use this method at first.
  • close() – To close the directory handle, use this method.

And, the directory class has two properties-

  • path – To get the path of the directory.
  • handle – To get the handle of the directory class.

Syntax:

dir(directory, context)

Parameters:

The Function has 1 required parameter and 1 optional parameter-

directory (Required): The directory that you want to be opened.

context (Optional): A context stream resource.

Return Values:

The function returns-

  • Instance of directory class – on success
  • Error – otherwise.

Examples:

Example 1:

<?php 
$dir_handle = dir("./images/");
echo "Handle: " . $dir_handle->handle . "<br />";
echo "Path: " . $dir_handle->path . "<br />";
while ($dir_handle->read()) {
  echo $dir_handle->read()."<br />";
}
$dir_handle->rewind();
while ($dir_handle->read()) {
    echo $dir_handle->read()."<br />";
}
$dir_handle->close();
?>

Output:

Handle: Resource id #3
Path: ./images/
..
1.jpg

2.jpg

3.jpg
..
1.jpg

2.jpg

3.jpg

Explanation:

Line 2: The “images” folder exists in the current directory. The dir() function returns the directory handle and we save it in $dir_handle function.

Line 3 & 4: These returns handle of the directory class and path of the directory.

Line 5-7: Using the handler, we use the read() method to list all the files and folder of this “image” folder.

Line 8: We want to print the files and folders again, So, we use rewind() function to reset the directory handle.

Line 9-11: Same as “Line 5-7” Line 12: We use the close() method to close the directory handle.

Notes on dir() Function:

  • The order in which directory entries are returned by the read method is system-dependent.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP dir() Function

dir() is a useful function to list files and folders in a directory. It is a built-in directory function.

Reference:

https://www.php.net/manual/en/function.dir.php