Page 355 - Beginning PHP 5.3
P. 355
Chapter 11: Working with Files and Directories
<?php
while ( $file = readdir( $handle ) ) {
if ( $file != “.” && $file != “..” ) echo “<li>$file</li>”;
}
closedir( $handle );
?>
</ul>
</body>
</html>
Figure 11-2 shows an example result.
Figure 11-2
How It Works
After displaying the page header and storing the path to the directory to scan in the $dirPath
variable, the script gets a handle on the directory:
if ( !( $handle = opendir( $dirPath ) ) ) die( “Cannot open the directory.” );
If the directory was successfully opened, its name is displayed in the page and an unordered list (ul)
HTML element is started. Next the script uses readdir() to loop through each entry in the directory
and, as long as the entry isn’t “.” or “..”, display it. The loop exits when readdir() returns false,
which occurs when the list of entries is exhausted:
while ( $file = readdir( $handle ) ) {
if ( $file != “.” && $file != “..” ) echo “<li>$file</li>“;
}
Finally, the script calls closedir() to close the directory, then finishes off the markup for the list and
the page.
317
9/21/09 9:10:17 AM
c11.indd 317
c11.indd 317 9/21/09 9:10:17 AM