Page 354 - Beginning PHP 5.3
P. 354
Part III: Using PHP in Practice
Working with Directories
PHP lets you work with directories in much the same way as files, using a variety of equivalent
functions. Some directory functions use a directory handle, whereas others use a string containing the
name of the directory with which you want to work. A directory handle is similar to a file handle; it ’ s a
special variable pointing to a directory, which you can obtain via the opendir() function:
$handle = opendir( “/home/james” );
If there ’ s a problem opening the directory (for example, if the directory doesn ’ t exist), opendir()
returns false instead of the directory handle. As you may have guessed, you can close a directory by
passing the directory handle to the function closedir() :
closedir( $handle );
The readdir() function expects a directory handle for an opened directory, and returns the filename
of the next entry in the directory:
$filename = readdir( $handle );
Each directory contains a list of entries for each of the files and subdirectories inside it, as well as entries
for . (representing the directory) and .. (the parent of the directory). PHP maintains an internal pointer
referring to the next entry in the list, just as a file pointer points to the position in a file where the next
file operation should occur.
Try It Out List Directory Entries
Here’s how to set up a loop to get all the files and folders inside a specified directory. Save the
following script as dir_list.php in your document root folder. Now change the $dirPath variable
in the file so that it contains the path to a real directory on your Web server. Open the script’s URL in
your Web browser to test it.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>Listing the contents of a directory</title>
<link rel=”stylesheet” type=”text/css” href=”common.css” />
</head>
<body>
<h1>Listing the contents of a directory</h1>
<?php
$dirPath = “/home/matt/images”;
if ( !( $handle = opendir( $dirPath ) ) ) die( “Cannot open the directory.” );
?>
<p><?php echo $dirPath ?> contains the following files and folders:</p>
<ul>
316
9/21/09 9:10:17 AM
c11.indd 316 9/21/09 9:10:17 AM
c11.indd 316