Sunday, November 23, 2025
HomeLanguagesPHP | dir() Function

PHP | dir() Function

The dir() function in PHP is an inbuilt function which is used to return an instance of the Directory class. The dir() function is used to read a directory, which includes the following:

  1. The given directory is opened.
  2. The two properties handle and path of dir() are available.
  3. Both handle and path properties have three methods: read(), rewind(), and close().

The path of the directory is sent as a parameter to the opendir() function and it returns an instance of the Directory class on success, or FALSE on failure.

Syntax:

dir($directory, $context)

Parameters Used: The dir() function in PHP accepts two parameters as described below.

  • $directory: It is a mandatory parameter which specifies the path of the directory.
  • $context: It is an optional parameter which specifies the behavior of the stream.

Return Value: It returns an instance of the Directory class on success, or FALSE on failure.

Errors And Exceptions:

  1. A NULL value is returned if the dir() is passed with wrong parameters.
  2. The order in which directory entries are returned by the read method is system-dependent.

Below programs illustrate the dir() function:

Program 1:




<?php
  
$dir_handle = dir("user/gfg");
  
while(($file_name = $dirhandle->read()) !== false) 
{ 
    echo("File Name : " . $file_name);
    echo "<br>" ; 
}
  
?>


Output:

File Name: gfg.jpg
File Name: ..
File Name: gfg.pdf
File Name: .
File Name: gfg.txt

Program 2:




<?php
  
$dir_handle = dir("user/gfg");
  
echo("Directory Path: " . $dir_handle->path . "<br>");
  
echo("Directory Handler ID: " . $dir_handle->handle . "<br>");
  
while(($file_name = $dir_handle->read()) !== false) 
{ 
   echo("File Name: " . $file_name);
   echo "<br>" ; 
} 
  
$dir_handle->close();
  
?>


Output:

Directory Path: user/gfg
Directory Handler ID: Resource id #2

File Name: gfg.jpg
File Name: ..
File Name: gfg.pdf
File Name: .
File Name: gfg.txt

Reference: http://php.net/manual/en/function.dir.php

RELATED ARTICLES

Most Popular

Dominic
32407 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6785 POSTS0 COMMENTS
Nicole Veronica
11932 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12000 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7168 POSTS0 COMMENTS
Thapelo Manthata
6864 POSTS0 COMMENTS
Umr Jansen
6852 POSTS0 COMMENTS