Team LiB
Previous Section Next Section

Displaying Directory Contents

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.

  1. Open a new file in your text editor and start a PHP block:

    <?
    
    
  2. 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!

  3. 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.

  4. You'll eventually place the results in a bulleted list inside a string called $file_list. Start that bulleted list now:

    $file_list = "<ul>";
    
  5. 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)) {
    
  6. Get rid of those . and .. filenames using an if statement:

    if (($file_name != ".") && ($file_name != "..")) {
    
  7. If $file_name is neither of the "dot" filenames, add it to $file_list using the concatenation assignment operator:

    $file_list .= "<li>$file_name";
    
  8. Close the if statement and the while loop:

    }
    }
    
    
  9. Add the closing tag to the bulleted list:

    $file_list .= "</ul>";
    
  10. Close the open directory:

    closedir($dir);
    
  11. Close your PHP block and then add some HTML to begin the display:

    ?>
    <HTML>
    <HEAD>
    <TITLE>Directory Listing</TITLE>
    </HEAD>
    <BODY>
    
  12. Mingle some HTML and PHP to print the name of the directory you just read:

    <P>Files in: <? echo "$dir_name"; ?></P>
    
  13. Print the file list, and then close your HTML tags so the document is valid:

    <? echo "$file_list"; ?>
    </BODY>
    </HTML>
    
  14. Save the file with the name listfiles.php.

Your code should look something like the code shown in the following figure.

Click To expand

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.

Click To expand

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.


Team LiB
Previous Section Next Section