Believe it or not, this script will be the most complicated in this chapter, and it has only 32 lines! The goal is to open a directory, find the names of all the files in the directory, and print the results in a bulleted list.
Open a new file in your text editor and start a PHP block:
Create a variable to hold the full path name of a directory:
$dir_name = "/Documents and Settings/Owner/Desktop/misc/";
| Note |
This directory is one that exists on my own machine. Substitute your own directory name so that this works for you! |
Create a handle and use the opendir() function to open the directory specified in step 2.
$dir = opendir($dir_name);
| Note |
The term handle is used to refer to the just-opened directory. |
You'll eventually place the results in a bulleted list inside a string called $file_list. Start that bulleted list now:
$file_list = "<ul>";
Start a while loop that uses the readdir() function to determine when to stop and start the loop. The readdir() function returns the name of the next file in the directory, and in this case assigns the value to a variable called $file_name:
while ($file_name = readdir($dir)) {
Get rid of those . and .. filenames using an if statement:
if (($file_name != ".") && ($file_name != "..")) {
If $file_name is neither of the "dot" filenames, add it to $file_list using the concatenation assignment operator:
$file_list .= "<li>$file_name";
Close the if statement and the while loop:
Add the closing tag to the bulleted list:
$file_list .= "</ul>";
Close the open directory:
closedir($dir);
Close your PHP block and then add some HTML to begin the display:
?> <HTML> <HEAD> <TITLE>Directory Listing</TITLE> </HEAD> <BODY>
Mingle some HTML and PHP to print the name of the directory you just read:
<P>Files in: <? echo "$dir_name"; ?></P>
Print the file list, and then close your HTML tags so the document is valid:
<? echo "$file_list"; ?> </BODY> </HTML>
Save the file with the name listfiles.php.
Your code should look something like the code shown in the following figure.
To test it, place the file in the document root of your web server, and then open your web browser and type http://127.0.0.1/listfiles.php.
Assuming that this worked, try it for other directories on your system. If a directory doesn't exist, the script won't return an error—it just won't have any results.
In the next section, you work with the fopen() and fclose() functions to open and close specific files.