Specifications
LISTING 16.3 browsedir.php—A Directory Listing of the Uploaded Files
<html>
<head>
<title>Browse Directories</title>
</head>
<body>
<h1>Browsing</h1>
<?
$current_dir = “/home/book/uploads/”;
$dir = opendir($current_dir);
echo “Upload directory is $current_dir<br>”;
echo “Directory Listing:<br><hr><br>”;
while ($file = readdir($dir))
{
echo “$file<br>”;
}
echo “<hr><br>”;
closedir($dir);
?>
</body>
</html>
This script makes use of the opendir(), closedir(), and readdir() functions.
The function opendir()is used to open a directory for reading. Its use is very similar to the
use of fopen() for reading from files. Instead of passing it a filename, you should pass it a
directory name:
$dir = opendir($current_dir);
The function returns a directory handle, again in much the same way as fopen() returns a file
handle.
When the directory is open, you can read a filename from it by calling readdir($dir),as
shown in the example. This returns false when there are no more files to be read. (Note that it
will also return false if it reads a file called “0”—you could, of course, test for this if it is
likely to occur.) Files aren’t sorted in any particular order, so if you require a sorted list, you
should read them into an array and sort that.
When you are finished reading from a directory, you call closedir($dir) to finish. This is
again similar to calling fclose() for a file.
Sample output of the directory browsing script is shown in Figure 16.3.
Interacting with the File System and the Server
C
HAPTER 16
16
INTERACTING WITH
THE
F
ILE SYSTEM
AND THE
SERVER
359
21 7842 CH16 3/6/01 3:40 PM Page 359










