PHP Tutorial - PHP opendir() Function






Definition

The opendir() function opens a directory handle.

Syntax

PHP opendir() Function has the following syntax.

opendir(path,context);

Parameter

ParameterIs RequiredDescription
pathRequired.Directory path to be opened
contextOptional.Context of the directory handle.

Return

PHP opendir() Function returns the directory handle resource on success. FALSE on failure.

Example

Open a directory, read its contents, then close:


<?php/* w ww . j a va 2 s  .  c  o m*/
$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 . "\n";
    }
    closedir($dh);
  }
}
?>




Example 2

The following code shows how to open a directory, list its files, reset directory handle, list its files once again, then close.


/*from   w w w  . j ava2 s . c  o  m*/
<?php
   $dir = "/images/";

   // Open a directory, and read its contents
   if (is_dir($dir)){
     if ($dh = opendir($dir)){
       // List files in images directory
       while (($file = readdir($dh)) !== false){
         echo "filename:" . $file . "<br>";
       }
       rewinddir();
       // List once again files in images directory
       while (($file = readdir($dh)) !== false){
         echo "filename:" . $file . "<br>";
       }
       closedir($dh);
     }
   }
?>