PHP Function Reference

PHP opendir() Function



The PHP opendir() function opens up a directory handle to be used in subsequent readdir(), rewinddir() and closedir() calls.

Syntax

opendir(path, context)

Parameters

path Required. Specify the directory path that is to be opened.
context Optional. Specify the context of the directory handle. Context is a set of options that can modify the behavior of a stream.

Return Value

Returns a directory handle resource on success, or false on failure.

Exceptions

Upon failure, an E_WARNING is emitted. This could be due to invalid directory path, permission restrictions, or filesystem errors.

Example: opendir() example

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

<?php
$dir = "/temp/images";

//opens the directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    
    //reading all entry from directory handle
    while (($file = readdir($dh)) !== false){
      echo "File Name: ".$file."\n";
    }
    
    //closing the directory handle
    closedir($dh);
  }
}
?>

The output of the above code will be:

File Name: fig1.png
File Name: fig2.png
File Name: Photo.jpg
File Name: .
File Name: ..
File Name: error.jpeg

❮ PHP Directory Reference