Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Open, Read and Close Directories

opendir(), readdir() and closedir()

opendir() - as the name suggests, opens a given directory. It accepts the directory name as the only parameter, and returns a directory handle - in much the same way that the open() function discussed earlier returns a file handle.

Once again you may find me using the term "filehandle", "file handle" or "file_handle" to refer to a "directory handle" (or "dir_handle", "dirhandle").... What is in a name?!

This directory handle is a system-generated ID for referencing a specific opened directory. The syntax for using the function is:

$dirHandle = opendir("directory to open");

An example:

$dir = opendir("/www/home/lessons/");

Once the directory is open, you can read its contents (files and sub-directories), one at a time, using the readdir() function.

The readdir() function accepts the directory handle and as said above, returns the name of the NEXT file/sub-directory in the directory in no particular order. The syntax:

$nextFile = readdir($dirHandle);

example - to read the next file in our previously opened directory:

$nextItem = readdir($dir);

Take note that the current directory (.) and the parent directory (..) are also listed.

The directory handle once again comes in handy when closing the directory using the closedir() function. The syntax is:

closedir($dirHandle);

To close our previously opened directory:

closedir($dir);

To list all files in the current directory (.), we'll use a while loop:

<?php
  $start_dir = ".";
  $dirHandle = opendir($start_dir);
  while($file = readdir($dirHandle)){
	echo $file."\n";
  }
  closedir($dirHandle);
?>

As it is, this has been a very long lesson and I have given you a larger-than-life dosage of PHP in one big scoop. I don't want you to choke on it. So I have an example that makes use of directories. I will not show this to you now. I yawwwwwn really must yawwwwwwnnnnnn... Goodnight!

<< Change, Make and Remove Directories | Back to the TOC >>

JamHitz Productions