PHP readdir() Function

Definition

The readdir() function returns the name of the next entry in a directory.

Syntax

PHP readdir() Function has the following syntax.

readdir(dir_handle);

Parameter

ParameterIs RequiredDescription
dir_handleOptional.Directory handle resource previously opened with opendir(). If this parameter is not specified, the last link opened by opendir() is assumed

Return

PHP readdir() Function returns the entry name (filename) on success. FALSE on failure.

Example

readdir() function takes the handle returned from opendir().

Each time you call readdir(), it returns the filename of the next file in the directory.

Once it reaches the end of the directory, it will return false.

Here is an example of how to list the contents of a directory:


<?PHP/* w w w.  j ava 2s .c o m*/
      $handle = opendir('/path/');

      if ($handle) {
             while (false !== ($file = readdir($handle))) {
                     print "$file \n";
             }
             closedir($handle);
     }
?>

The code above generates the following result.

Example 2

Open a directory, read its contents, then close:


<?php//w  w  w  .j a  v a  2s  .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);
  }
}
?>




















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions