Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

opendir()

Example

Open a directory, read its contents, and subsequently close it.

<?php
$dir = “/images/”;

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
      echo “filename:” . $file . “<br>”;
    }
    closedir($dh);
  }
}
?>

Result:

filename: cat.gif
filename: dog.gif
filename: horse.gif

Definition and Usage

The opendir() function opens a directory and returns a directory handle.

Syntax

opendir(path, context)

Parameter Values

Parameter

Description

path

Required. Specifies the path of the directory to be opened.

context

Optional. Specifies the context for the directory handle, which is a set of options that can alter the behavior of the stream.

Technical Details

Return Value:

Returns the directory handle resource on success, or FALSE on failure. Throws an E_WARNING level error if the path is not a valid directory, or if the directory cannot be opened due to permission issues or filesystem errors. To suppress error output from opendir(), prefix the function name with ‘@’.

PHP Version:

4.0+

PHP Changelog:

PHP 5.0: The path parameter now supports the ftp:// URL wrapper.