Page 360 - Beginning PHP 5.3
P. 360
Part III: Using PHP in Practice
Try It Out Traversing a Directory Hierarchy
As you learned in Chapter 7, recursion is particularly useful when a script has to perform repetitive
operations over a set of data of unknown size, and traversing a directory hierarchy is a very good
example.
A directory may hold subdirectories as well as files. If you want to create a script that lists all the files
and subdirectories under a given directory — including subdirectories of subdirectories, and so on —
you need to write a recursive function, as follows:
1. Read the entries in the current directory.
2. If the next entry is a file, display its name.
3. If the next entry is a subdirectory, display its name, then call the function recursively to read the
entries inside it.
As you can see, the third step repeats the whole process by itself, when necessary. The recursion
continues until there are no more subdirectories left to traverse.
To try out this technique, first save the following script as directory_tree.php. Now change the
$dirPath variable at the top of the script to point to a folder on your Web server’s hard drive, and
open the script’s URL in your Web browser. You should see a page similar to Figure 11-3.
<!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”;
function traverseDir( $dir ) {
echo “<h2>Listing $dir ...</h2>”;
if ( !( $handle = opendir( $dir ) ) ) die( “Cannot open $dir.” );
$files = array();
while ( $file = readdir( $handle ) ) {
if ( $file != “.” && $file != “..” ) {
if ( is_dir( $dir . “/” . $file ) ) $file .= “/”;
$files[] = $file;
}
}
sort( $files );
echo “<ul>”;
foreach ( $files as $file ) echo “<li>$file</li>”;
322
9/21/09 9:10:19 AM
c11.indd 322 9/21/09 9:10:19 AM
c11.indd 322