How to list the contents of a directory
Firstly we need to define the full server path to the folder:
$path = “/home/user/public/foldername/”;
To open the directory we use PHPs opendir. Placing an @ sign in front prevents any error messages being shown, so you might want to exclude that until you test the script.
$dir_handle = @opendir($path) or die(“Unable to open $path”);
Now that the directory is open we can loop through the files and display them using readdir
while (false !== ($file = readdir($dir_handle))) {
echo “<a href=\”$file\”>$file</a><br />”;
}
You’ll notice that the directory listing file itself is displayed. To prevent that from being shown we would add the following line before we echo the results:
if($file == “index.php”) continue;
Finally, for good measure we close the directory.
closedir($dir_handle);
That’s all there is to it. You can of course format the results any way you wish.
The script in full is as follows:
<?php
// Define the full path to your folder
$path = "/home/user/public/foldername/";
// Open the folder
$dir_handle = @opendir($path) or die("Unable to open $path");
// Loop through the files
while (false !== ($file = readdir($dir_handle))) {
// Prevent this file itself being shown
if($file == "index.php")
continue;
// Display the results
echo "<a href=\"$file\">$file</a><br />";
}
// Close it
closedir($dir_handle);
?>









Leave a Comment