Home »
PHP
PHP Directory dir() Function (With Examples)
In this tutorial, we will learn about the PHP dir() function with its usage, syntax, parameters, return value, and examples.
By IncludeHelp Last updated : December 31, 2023
PHP dir() function
The dir() function is an instance of the directory class, it is used to read the directory, it includes handle and path properties – which can be used to get the resource id and path to the directory. Both handle and path have read(), rewind(), and close() methods.
Syntax
The syntax of the dir() function:
dir(directory,context);
Parameters
The parameters of the dir() function:
- directory – It is used to specify the path to the directory to be opened.
- context – It is an optional parameter; it defines the context (a set of options that can modify the behavior of the stream).
Return Value
On success – it returns an instance to the directory, on fail – it returns "FALSE".
PHP dir() Function Example
PHP code to demonstrate example of dir() function.
<?php
//path to current working directory
$cwd = dir(getcwd());
echo "Directory handle: " . $cwd->handle . "<br>";
echo "Current path: " . $cwd->path . "<br>";
//reading & printing the filenames using dir()
while (($file = $cwd->read()) !== false) {
echo "File: " . $file . "<br>";
}
//closing the dir instance
$cwd->close();
?>
Output
The output of the above example is:
Directory handle: Resource id #5
Current path: /home
File: .
File: ..
File: main.php
Reference: PHP dir() function
To understand the above example, you should have the basic knowledge of the following PHP topics: