PHP Function Reference

PHP dir() Function



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

  • The specified directory is opened.
  • The two properties path and handle of the directory class are available.
  • Both handle and path properties can be used with three directory methods: readdir(), rewind() and close().

Syntax

dir(directory, context)

Parameters

directory Required. Specify the directory to open.
context Optional. Specify the context stream resource. Context is a set of options that can modify the behavior of a stream.

Return Value

Returns an instance of Directory, or null with wrong parameters, or false in case of another error.

Example:

The example below shows the usage of dir() function.

<?php
$d = dir("/temp/images");

echo "Directory Path: ".$d->path."\n";
echo "Directory Handle ID: ".$d->handle."\n";

//reading all entry from directory handle
while (($file = $d->read()) !== false) {
  echo "File Name: ".$file."\n";
}

//closing the directory handle
$d->close();
?>

The output of the above code will be:

Directory Path: /temp/images
Directory Handle ID: Resource id #5
File Name: fig1.png
File Name: fig2.png
File Name: Photo.jpg
File Name: .
File Name: ..
File Name: error.jpeg

❮ PHP Directory Reference