PHP Tutorial - PHP readdir() Function


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


PHP readdir() Function has the following syntax.



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


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


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 ww  .j ava  2 s  . c  om
      $handle = opendir('/path/');

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

The code above generates the following result.

Example 2

Open a directory, read its contents, then close:

<?php/*from  w  w  w . ja v  a  2 s  .co  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";

Example 3

The following code shows how to get directory recursively.

<?php// ww  w.ja  v a 2 s .c  o m
    function directorySize($directory) {

        // Open the directory and read its contents.
        if ($dh = @opendir($directory)) {

            // Iterate through each directory entry.
            while (($filename = readdir ($dh))) {

                // Filter out some of the unwanted directory entries
                if ($filename != "." && $filename != "..")

                    // File, so determine size and add to total
                    if (is_file($directory."/".$filename))
                        $directorySize += filesize($directory."/".$filename);

                    // New directory, so initiate recursion
                    if (is_dir($directory."/".$filename))
                        $directorySize += directorySize($directory."/".$filename);

        return $directorySize;


    $directory = '/usr/';
    $totalSize = round((directory_size($directory) / 1048576), 2);