iNET Interactive - Online Advertising Agency
          
   Home    Authors    About    Login    Contact Us
   Search:   
Advanced Search     
  Articles

  ASP (26)
  ASP.NET (19)
  C and C++ (4)
  CFML (2)
  CGI and Perl (16)
  Flash (2)
  Java (7)
  JavaScript (28)
  PHP (92)
  MySQL (13)
  MSSQL (3)
  HTML (34)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

May 12, 2008
Film Makers, Bands and Comedians Welcome on MySpace
About
 
May 12, 2008
Software Engineering for Ajax
WebReference.com
 
May 12, 2008
What is the Head Tag For?
About
 
May 11, 2008
Improving accessibility for motor impaired users
WebDevTips UK
 
May 11, 2008
10 ways to orientate users on your site
WebDevTips UK
 
May 11, 2008
Web Design Clinic - Rros restoration camp 2006
About
 
Courtesy of moreover.com
 
Want to receive new articles via e-mail? Click here!
/Home /PHP

How to list the contents of a directory 

  Views:    5771
  Votes:    7
by Dan Bailey 12/04/03 Rating: 

Synopsis:

This article will show you how to run through a directory and list the files it contains
Pages: 
The Article

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);

?>

Pages: 



 
  Sponsors