Categories
PHP

Reading Directories Contents

How to browse the file system with the help of PHP functions.

  1. dir()
  2. scandir()
  3. opendir(), readdir(), and closedir()

The dir class

<?php
 //Syntax
 dir(string $directory,
     ?resource $context = null
    ): Directory|false

Since PHP 3, PHP comes with a built-in class that offers several methods to access the file system. It is possible to get a list of all entries in a directory.

<?php
 $dirPath = 'uploads/gif/';
 $dh = dir($dirPath);
 if ($dh === false)
  exit ('Error: unable to open dir');
 while (false !== ($entry = $dh->read())) {
  echo $entry . '<br>';
 }
 $dh->close();

You instantiate the class without the keyword new, just by providing the desired path as a parameter. Then the method read() iterates through the list of entries. The preceding code does exactly this and prints out the contents of the current directory.

.
..
abc.gif
dog.gif
image.gif
tamin.gif

Note that the two directory entries . (current directory) and .. (parent directory, if you are not in the root directory) are printed out.

scandir()

The scandir() function list files and directories inside the specified path and returns an array of files and directories from the path/directory.

<?php
 //Syntax
 scandir(string $directory,
   int $sorting_order = SCANDIR_SORT_ASCENDING,
   ?resource $context = null
       ): array|false

This function accepts three parameters:

  1. $directory the target directory for scanning
  2. $sorting_order to set sort order, default is alphabetical in ascending order, set SCANDIR_SORT_DESCENDING for descending order and SCANDIR_SORT_NONE for unsorted result.
  3. context

Example: Using scandir() function

<?php
 $dirPath = 'uploads/gif/';
 $entries = scandir($dirPath);
 if ($entries === false)
  exit ("Error: unable to open $dirPath");
 foreach ($entries as $entry) {
  echo $entry .'<br>';
 }

The above example output is:

.
..
abc.gif
dog.gif
image.gif
tamin.gif

opendir(), readdir() and closedir()

The opendir() function returns a “directory handle” to the directory named in the function call. The directory handle is then used by the readdir() function to iterate over the directory, returning a single entry each time it is invoked. Once done, the closedir() function closes the directory handle.

<?php
 $dirPath = 'uploads/gif/';

 if ( ! is_dir($dirPath) )
  exit ("Error: $dirPath is not a directory");

 $handle = opendir($dirPath);
 if ($handle === false)
  dir ("Error: unable to open $dirPath");

 while (($entry = readdir($handle)) !== false) {
  echo $entry .'<br>';
 }
 
 closedir($handle);

The above code outputs the following result:

.
..
abc.gif
dog.gif
image.gif
tamin.gif

Working with Files in PHP: