PHP script to list files within a directory


9/8/02
 

PHP script to list files within a directory

I spent some time reading the >>PHP Manual to look for clues as to how to search for files and sub-directories within a directory. After a little experimentation I got this to work:
<?php

// A test script to search list the files within a directory

// author = Martin Bush, South Bank University
// date = 11th August 2002
// filename = list-files-in-directory.php3
// version = 1.1
// history = -

echo "Testing file listing... <p>";

$current_directory = @opendir("/users/cam/cam/bushm/.public_html");

echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";
echo readdir($current_directory) . "<br>";

echo "<p>Well - did it work?";

?>
 
It echoed a list of the contents of my .public_html directory, and when it had run out of things to list it simply echoed blank lines - which means I could use a while loop containing a readdir($current_directory) that would terminate when a null string was returned, and of course I could write the list to a text file instead of echoing it.

Where does this get me? Well, it means that I may not need to have an additional cgi script after all. But I'm still left with the problem of how to find all the files in all of the sub-directories. Looking at the appropriate section in the PHP manual, I can see how to test whether a "file" is in fact a sub-directory, and I can see how to change directory into that sub-directory so that I can repeat the process. No doubt the best solution to this problem would be a recursive algorithm. It doesn't seem straight-forward to me at the moment, but I'm sure it's doable.

 
 

<<contents ^top^ next>>