Sunday, November 23, 2025
HomeLanguagesPHP | dir() (Get instance of the Directory)

PHP | dir() (Get instance of the Directory)

The dir() function in PHP used to find the instance of a Directory class. This function read directory, which includes the following:

  • The given directory is opened.
  • The two properties handle and path of dir() are available.
  • The handle property can be used with other directory functions such as readdir(), rewinddir(), closedir(). The path property is set to path the directory that was opened
  • Both handle and path properties have three methods: read(), rewind(), and close().

Syntax :

 dir(string $directory, resource $context)

Parameters Used :
The dir() function accepts two parameters. They are illustrated as follows:

  1. $directory : It is a required parameter. It specifies the directory to be opened.
  2. $context : It is an optional parameter. It contains references to all modules in the
    directory that can be required with a request matching the regular expression.

Return Value :
The above function will return an instance of the Directory class on success. Otherwise will return FALSE on Failure.

Note:

  1. The order in which directory entries are returned by the read method is system-dependent.
  2. This function defines the internal class Directory, meaning that we will not be able to define our own classes with that name.

Example :
Below is the implementation of above explained function :




<?php
   
// getcwd() function will return 
// the current working directory
$directory = dir(getcwd());
   
// Exploring directories and their contents
echo "Handle: " . $directory->handle . "\n";
echo "Path: " . $directory->path . "";
   
// If the evaluation is true then, the loop will
// continue otherwise any directory entry with name
// equals to FALSE will stop the loop .
while (($file = $directory->read()) !== false) {
       
    // printing Filesystem objects/functions with PHP
    echo "filename: " . $file . "\n";
}
$directory->close();
?>


Output :

Handle: Resource id #3
Path: /storage/ssd2/630/2687630/public_html
filename: .
filename: ..
filename: bookkart
filename: index.php
filename: upload.html
filename: hello.html
filename: file-upload-manager.php
filename: tmp.php
filename: raj.php
filename: gfgchecking
filename: 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