Ads

How to: Display all files in an directory

Alright, Now listning the files in a directory into a list with PHP can be very simple. Follow me here.

First off we have to set our 'path' or 'directory'. I have set mine to the files folder. You can set that to whatever but it must be the full path. If you dont know how to findout your full path from your server room, have a look at $_SERVER[DOCUMENT_ROOT], you may find others at this tutorial. Located here.


CODE
    // fefine the full path to your folder 
    $path = "/home/user/public_html/files";




Next is how the server opens the folder.

CODE
    // Open the folder
    $dir_handle = @opendir($path) or die("Unable to open $path");


What this does is it takes the path you have specified and tryes to open it. If it cannot open it for some reason, it will display "Unable to open 'your path'".

You may think, what does this do. Mabe you dont. Who knows. Anyway what this does it that, it takes the path you have specified if it exists and reads the directory to see what it has inside it. Then loops that to get all of the files.

CODE
    // Loop through the files
    while ($file = readdir($dir_handle)) {




This basically removes the ./ and ../ from the listing. You would usally find those in a regular file listing from a windows/unix server. Anyway the rest just displays the title and a link to the files included in that path you have specified earlier.

CODE
    if($file == "." || $file == ".." || $file == "index.php" )
 
        continue;
        echo "<a href="$file">$file</a>";
 
    }




Last but not least, we have to close the connection to the folder. Which is very simple.

CODE
    // Close connection to directory
    closedir($dir_handle);




And finally our full code put together.

CODE
<?php
    
// Define the full path to your folder from root
    
$path "/home/user/public_html/files";
 
    
// Open the folder
    
$dir_handle = @opendir($path) or die("Unable to open $path");
 
    
// Loop through the files
    
while ($file readdir($dir_handle)) {
 
    if(
$file == "." || $file == ".." || $file == "index.php" )
 
        continue;
        echo 
"<a href="$file">$file</a>";
 
    }
    
// Close connection to directory
    
closedir($dir_handle);
?> 



Very simple, there is so much more you can do other then that.

Monday September 10, 2007 - 409 reads