opendir

(PHP 3, PHP 4, PHP 5)

opendir -- 打开目录句柄

说明

resource opendir ( string path [, resource context] )

打开一个目录句柄,可用于之后的 closedir()readdir()rewinddir() 调用中。

参数

path

要打开的目录路径

context

context 参数的说明见手册中的 Streams API 一章。

返回值

如果成功则返回目录句柄的 resource,失败则返回 FALSE

如果 path 不是一个合法的目录或者因为权限限制或文件系统错误而不能打开目录,opendir() 返回 FALSE 并产生一个 E_WARNING 级别的 PHP 错误信息。可以在 opendir() 前面加上“@”符号来抑制错误信息的输出。

更新日志

版本说明
5.0.0 path 支持 ftp:// URL wrapper
4.3.0 path 可以是任何支持目录列表的 URL,不过在 PHP 4 中只有 file:// URL wrapper 支持此功能

范例

例 1. opendir() 例子

<?php
$dir
= "/etc/php5/";

// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
    if (
$dh = opendir($dir)) {
        while ((
$file = readdir($dh)) !== false) {
            echo
"filename: $file : filetype: " . filetype($dir . $file) . "\n";
        }
        
closedir($dh);
    }
}
?>

上例的输出类似于:

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir


add a note add a note User Contributed Notes
lolwut
13-May-2007 01:00
I sometimes find this useful. Hope you will too.

<?php
//list_by_ext: returns an array containing an alphabetic list of files in the specified directory ($path) with a file extension that matches $extension

function list_by_ext($extension, $path){
  
$list = array(); //initialise a variable
  
$dir_handle = @opendir($path) or die("Unable to open $path"); //attempt to open path
  
while($file = readdir($dir_handle)){ //loop through all the files in the path
      
if($file == "." || $file == ".."){continue;} //ignore these
      
$filename = explode(".",$file); //seperate filename from extenstion
      
$cnt = count($filename); $cnt--; $ext = $filename[$cnt]; //as above
      
if(strtolower($ext) == strtolower($extension)){ //if the extension of the file matches the extension we are looking for...
          
array_push($list, $file); //...then stick it onto the end of the list array
      
}
   }
   if(
$list[0]){ //...if matches were found...
  
return $list; //...return the array
  
} else {//otherwise...
  
return false;
   }
}

//example usage
if($win32_exectuables = list_by_ext("exe", "C:\WINDOWS")){
  
var_dump($win32_exectuables);
} else {
   echo
"No windows executables found :(\n";
}

?>
Michael mt1955 (a) gmail.com
11-May-2007 02:59
# simple directory walk with callback function

<?php
function callbackDir($dir)
{
  
# do whatever you want here
  
echo "$dir\n";
}

function
walkDir($dir,$fx)
{
 
$arStack = array();
 
$fx($dir);
  if( (
$dh=opendir($dir)) )
  { while( (
$file=readdir($dh))!==false )
   { if(
$file=='.' || $file=='..' ) continue;
     if(
is_dir("$dir/$file") )
     { if( !
in_array("$dir/$file",$arStack) ) $arStack[]="$dir/$file";
     }
   }
  
closedir($dh);
  }
  if(
count($arStack) )
  { foreach(
$arStack as $subdir )
   {
walkDir($subdir,$fx);
   }
  }
}

walkDir($root,callBackDir);
?>
Dblurred
08-May-2007 12:04
In reponse to Tozeiler.  Nice short directory dump.  However, that displays the "." and "..".  This removes those.  It also makes an ordered list in case I needed to be on the phone while looking at the page.  Easy to call out.

<?php

$path
= "your path";
$dh = opendir($path);
$i=1;
while ((
$file = readdir($dh)) !== false) {
   if(
$file != "." && $file != "..") {
       echo
"$i. <a href='$path/$file'>$file</a><br />";
      
$i++;
   }
}
closedir($dh);
?>
samantha dot vincent at gmail dot com
02-May-2007 06:46
Using Apache 2.2.4 with PHP and MySQL I was trying to connect to a Novell Netware drive using opendir("R:/") where R: was pointing to a Netware resource on another server. The error returned was

Warning: opendir(R:/) [function.opendir]: failed to open dir: No such file or directory in path/to/my/phpfile/containing/opendir on line 34.

Basically it is a problem with Netware rights and users and how the apache service was trying to connect to the resource.

To get everything working as expected in the end we set up a Windows user account eg: webhost with the same password as a Netware account with username webhost, set the Netware account to have rights to the resource R:/ (we just used admin rights), and set the apache service to run as the webhost user using the username password combo.

Hope this helps someone else out.
.....alexander[at]gmail.com
14-Apr-2007 05:13
This is a script that prints all the file and directory names  on your server no matter where the script file is located
(could take a lot of time to execute, if you have a lot of directories and files...)
Hope someone finds it useful...

<?php
print $_SERVER['DOCUMENT_ROOT'] . "<br />";
$root = @opendir($_SERVER['DOCUMENT_ROOT']);
$dirs = array();

while(
$file = readdir($root)){
   print
$file;
   if((
is_dir($file) || !stristr($file, ".")) && $file!="." && $file!=".."){
        
$dirs[] = ($_SERVER['DOCUMENT_ROOT'] . "/" . $file);
   print
"(adding directory)";
   }
   print 
"<br />";
}
closedir($root);

print
"<br /><br />Inside Dirs: (" . (count($dirs)) . ")<br />";

$i = 0;
   while(
$i < count($dirs)){

      
$d = @opendir($dirs[$i]);
       print
"<br /><br />Directory: " . $dirs[$i] . "<br />";

       while(
$f = readdir($d)){
           print
$f;

           if((
is_dir($f) || !stristr($f, ".")) && $f!="." && $f!=".."){
                
$dirs[] = $dirs[$i]  . "/" $f;
           print
"(adding directory)";
           }

           print
"<br />";
       }
      
closedir($d);

      
$i = $i + 1;
   }
$i = $i - 1;

?>
NerdyDork
08-Feb-2007 04:36
Here is a snippet to create a site map of all html files in a folder:

<?php
  
// read all html file in the current directory
  
if ($dh = opendir('./')) {
      
$files = array();
       while ((
$file = readdir($dh)) !== false) {
           if (
substr($file, strlen($file) - 5) == '.html') {
              
array_push($files, $file);
           }
       }
      
closedir($dh);
   }
  
  
// Sort the files and display
  
sort($files);
   echo
"<ul>\n";
   foreach (
$files as $file) {
      
$title = Title($file);
       echo
"<li><a href=\"$file\" title=\"$title\">$title</a></li>\n";
   }
   echo
"</ul>\n";
  
  
// Function to get a human readable title from the filename
  
function Title($filename) {
      
$title = substr($filename, 0, strlen($filename) - 5);
      
$title = str_replace('-', ' ', $title);
      
$title = ucwords($title);
       return
$title;
   }
?>
frogstarr78 at yahoo dot com
21-Jan-2007 08:30
Here's a function that will recrusively turn a directory into a hash of directory hashes and file arrays, automatically ignoring "dot" files.

<?php
function hashify_directory($topdir, &$list, $ignoredDirectories=array()) {
   if (
is_dir($topdir)) {
       if (
$dh = opendir($topdir)) {
           while ((
$file = readdir($dh)) !== false) {
               if (!(
array_search($file,$ignoredDirectories) > -1) && preg_match('/^\./', $file) == 0) {
                   if (
is_dir("$topdir$file")) {
                       if(!isset(
$list[$file])) {
                          
$list[$file] = array();
                       }
                      
ksort($list);
                      
hashify_directory("$topdir$file/", $list[$file]);
                   } else {
                      
array_push($list, $file);
                   }
               }
           }
          
closedir($dh);
       }
   }
}
?>

e.g.
<?php
$public_html
["StudentFiles"] = array();
hashify_directory("StudentFiles/", $public_html["StudentFiles"]);
?>
on the directory structure:
./StudentFiles/tutorial_01/case1/file1.html
./StudentFiles/tutorial_01/case1/file2.html
./StudentFiles/tutorial_02/case1/file1.html
./StudentFiles/tutorial_02/case2/file2.html
./StudentFiles/tutorial_03/case1/file2.html
etc...
becomes:
<?php
print_r
($public_html);
/*
outputs:
array(
  "StudentFiles" => array (
       "tutorial_01" => array (
             "case1" => array( "file1.html", "file2.html")
       ),
       "tutorial_02" => array (
             "case1" => array( "file1.html"),
             "case2" => array( "file2.html")
       ),
       "tutorial_03" => array (
             "case1" => array( "file2.html")
       )
  )
)
*/
?>
I'm using it to create a tree view of a directory.
phpguy at mailstop dot yogelements dot omitme dot com
13-Dec-2006 09:40
An issue that I ran into is that opendir() could care less if you've got server authentication set on sub directories and so any such authentication is bypassed completely when accesses in this way. I did solve it for my application of a pretty file manager, by redirecting to all sub directories thusly:
$fdir = "./subdirectory_I_want_to_visit/";
if ($fdir != './') { //basically where we are or the parent
   //redirect the browser to force authentication check on any subdirectories
   header("Location: http://my.domain.com".dirname($_SERVER["PHP_SELF"]).substr($fdir,2));
   exit;
} else {
   $dir = opendir($fdir);
}
tony at glccom dot com
01-Nov-2006 05:49
John & I have edited the code posted by hendrik dot wermer at gmx dot de on 07-Feb-2005 06:06

This Code now allows for downloads form sub directories. We also used CSS to make the page's look customizable.

You can view the example at: http://www.asterikast.com/code/dirlist.txt
anon at no thing dot com
23-Oct-2006 04:55
In response to previous post,
you can use realpath() to fix the '/../../../' problem.
Christian
26-Jul-2006 10:10
Pointing on the previous post, I'd like to say the following.

You can use opendir on all valid (existant and reachable) folders.
This counts not only for windows but also for linux.
Under linux, you can also read root folders etc.

To avoid access to non-public data, you should check the given parameter for opendir before executing opendir.

Let's say you have this:

/home/users/mrsmith/
/home/users/mrsmith/info.txt
/home/users/mrsmith/test/photo.jpg
/home/users/mradmin/private.txt

Now you don't want mrsmith to access mradmin's folders/files.
In that case you could/should define the path where the data MUST be inside.

Attention:
Don't check the data with substr though, it's not a secure solution.
Exploit example: /home/users/mrsmith/../mradmin/
Exploit example2: /home/users/mrsmith/../../../../../../../../../../../../../dev/

I'd do a case sensitive regex match.
So after the first folder there may not be a subfolder named ".." because that would jump one folder back.

I hope this isn't too offtopic or so but I think it's important to think of that when creating file systems.
tim2005
13-May-2006 12:04
Hello,

A friend of mine is running a webhost, I think i found a security leak with this script:

<?php
function select_files($dir, $label = "", $select_name, $curr_val = "", $char_length = 30) {
  
$teller = 0;
   if (
$handle = opendir($dir)) {
      
$mydir = ($label != "") ? "<label for=\"".$select_name."\">".$label."</label>\n" : "";
      
$mydir .= "<select name=\"".$select_name."\">\n";
      
$curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $curr_val;
      
$mydir .= ($curr_val == "") ? "  <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
       while (
false !== ($file = readdir($handle))) {
          
$files[] = $file;
       }
      
closedir($handle);
      
sort($files);
       foreach (
$files as $val) {
           if (
is_file($dir.$val)) { // show only real files (ver. 1.01)
              
$mydir .= "    <option value=\"".$val."\"";
              
$mydir .= ($val == $curr_val) ? " selected>" : ">";
              
$mydir .= (strlen($val) > $char_length) ? substr($val, 0, $char_length)."...\n" : $val."\n";
              
$teller++;   
           }
       }
      
$mydir .= "</select>";
   }
   if (
$teller == 0) {
      
$mydir = "No files!";
   } else {
       return
$mydir;
   }
}

echo
select_files("C:/winnt/", "", "", "", "60");
?>

Now i can see hist files in his windows dir. Is this a leak? and is it fixable? I'll report this as bug too!

Tim2005
tozeiler
15-Apr-2006 08:34
"opendir" said:
------------------------------------------------------------------

23-Jan-2006 08:04
I Just wanted a directory list and a clickable link to download the files

<snip>
------
<?
echo ("<h1>Directory Overzicht:</h1>");

function
getFiles($path) {

<
snip complicated function contents>

------------------------------------------------------------------
Here's a more straightforward way to linkify $path/files:

<?php

echo "<h1>Directory Overzicht:</h1>";

$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
   echo "<a href='
$path/$file'>$file</a><br />";
}
closedir($dh);

?>
23-Jan-2006 03:04
I Just wanted a directory list and a clickable link to download the files because my plesk server does not give me this function. I edited the script a little bit.

Many thanks from a script-noob

------
<?
echo ("<h1>Directory Overzicht:</h1>");

function
getFiles($path) {
  
//Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
   //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
   //relative to each other in the order presented by readdir()
  
$files = array();
  
$fileNames = array();
  
$i = 0;
  
   if (
is_dir($path)) {
       if (
$dh = opendir($path)) {
           while ((
$file = readdir($dh)) !== false) {
               if (
$file == "." || $file == "..") continue;
              
$fullpath = $path . "/" . $file;
              
$fkey = strtolower($file);
               while (
array_key_exists($fkey,$fileNames)) $fkey .= " ";
              
$a = stat($fullpath);
              
$files[$fkey]['size'] = $a['size'];
               if (
$a['size'] == 0) $files[$fkey]['sizetext'] = "-";
               else if (
$a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
               else if (
$a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
               else
$files[$fkey]['sizetext'] = $a['size'] . " bytes";
              
$files[$fkey]['name'] = $file;
              
$files[$fkey]['type'] = filetype($fullpath);
              
$fileNames[$i++] = $fkey;
           }
          
closedir($dh);
       } else die (
"Cannot open directory:  $path");
   } else die (
"Path is not a directory:  $path");
  
sort($fileNames,SORT_STRING);
  
$sortedFiles = array();
  
$i = 0;
   foreach(
$fileNames as $f) $sortedFiles[$i++] = $files[$f];
  
   return
$sortedFiles;
}

$files = getFiles("./");
foreach (
$files as $file) print "&nbsp;&nbsp;&nbsp;&nbsp;<b><a href=\"$file[name]\">$file[name]</a></b><br>\n";
?>
mstabile75 at gmail dot com
28-Dec-2005 04:26
In my previous post I ran into a problem with the "global" definition of $directorylist.  If I called the function more than once on the same page it would combine the file lists. I looked at Lasse Dalegaard's example and used the following solution.

remove global definition
     global $directorylist;

REPLACE
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
  
filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
}
?>
WITH
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
  
$list2 = filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
   if(
is_array($list2)) {
      
$directorylist = array_merge($directorylist, $list2);
   }
}
?>
mstabile75 at gmail dot com
27-Dec-2005 03:04
<?php
/* The below function will list all folders and files within a directory
It is a recursive function that uses a global array.  The global array was the easiest
way for me to work with an array in a recursive function
*This function has no limit on the number of levels down you can search.
*The array structure was one that worked for me.
ARGUMENTS:
$startdir => specify the directory to start from; format: must end in a "/"
$searchSubdirs => True/false; True if you want to search subdirectories
$directoriesonly => True/false; True if you want to only return directories
$maxlevel => "all" or a number; specifes the number of directories down that you want to search
$level => integer; directory level that the function is currently searching
*/
function filelist ($startdir="./", $searchSubdirs=1, $directoriesonly=0, $maxlevel="all", $level=1) {
  
//list the directory/file names that you want to ignore
  
$ignoredDirectory[] = ".";
  
$ignoredDirectory[] = "..";
  
$ignoredDirectory[] = "_vti_cnf";
   global
$directorylist;    //initialize global array
  
if (is_dir($startdir)) {
       if (
$dh = opendir($startdir)) {
           while ((
$file = readdir($dh)) !== false) {
               if (!(
array_search($file,$ignoredDirectory) > -1)) {
                 if (
filetype($startdir . $file) == "dir") {
                      
//build your directory array however you choose;
                       //add other file details that you want.
                      
$directorylist[$startdir . $file]['level'] = $level;
                      
$directorylist[$startdir . $file]['dir'] = 1;
                      
$directorylist[$startdir . $file]['name'] = $file;
                      
$directorylist[$startdir . $file]['path'] = $startdir;
                       if (
$searchSubdirs) {
                           if (((
$maxlevel) == "all") or ($maxlevel > $level)) {
                              
filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
                           }
                       }
                   } else {
                       if (!
$directoriesonly) {
                          
//if you want to include files; build your file array 
                           //however you choose; add other file details that you want.
                        
$directorylist[$startdir . $file]['level'] = $level;
                        
$directorylist[$startdir . $file]['dir'] = 0;
                        
$directorylist[$startdir . $file]['name'] = $file;
                        
$directorylist[$startdir . $file]['path'] = $startdir;
     }}}}
          
closedir($dh);
}}
return(
$directorylist);
}
$files = filelist("./",1,1); // call the function
foreach ($files as $list) {//print array
  
echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
}
?>
chrys at mytechjournal dot com
10-Dec-2005 07:16
I wrote a function to recursively delete files from a starting directory.  I had to do this because my server doesn't allow me to delete files that apache writes because I don't have permissions, so... I let apache do the work.

<?php
$dir
= "/path/to/base/dir";

recursive_delete($dir);

function
recursive_delete( $dir )
{
       if (
is_dir($dir)) {
           if (
$dh = opendir($dir)) {
               while ((
$file = readdir($dh)) !== false ) {
                       if(
$file != "." && $file != ".." )
                       {
                               if(
is_dir( $dir . $file ) )
                               {
                                       echo
"Entering Directory: $dir$file<br/>";
                                      
recursive_delete( $dir . $file . "/" );
                                       echo
"Removing Directory: $dir$file<br/><br/>";
                                      
rmdir( $dir . $file );
                               }
                               else
                               {
                                       echo
"Deleting file: $dir$file<br/>";
                                      
unlink( $dir . $file );
                               }
                       }
               }
              
closedir($dh);
           }
       }
}
?>
neale-php at woozle dot org
30-Nov-2005 05:41
oryan's example is still sub-optimal, even if people using it never ever substitute a variable for directory.

Just use PHP's glob() function, which will be faster and more efficient anyway since it doesn't have to launch a shell and run the ls program (that's what the shell_exec does).

$result = glob("directory/*");
oryan at zareste dot com
01-Nov-2005 11:19
There might be a bit of truth to that.  If, by chance, the webmaster made a form saying "type a random directory name here" and used that in the function, there'd be a problem.  So let's eliminate the 'function' part

$files=shell_exec("ls directory");
$result=explode("\n",$files);

'$result' will now be an array of the directory files.  You can use variables in the shell_exec command, but don't use anything that could be user-sent.
aligma at gmail dot com
01-Nov-2005 03:54
The example given by oryan at zareste dot com may also be a "simpler faster way" of creating security holes in your code. The function listed above prevents risking execution of abitrary shell commands listed after a semicolon (;) in your directory name.
Example: $directory = '.;rm -rf /';
Result: List this directory, erase contents of filesystem.
oryan at zareste dot com
31-Oct-2005 01:33
There's a simpler faster way to get a whole directory if you're using PHP 4.  This function uses shell_exec - http://us3.php.net/shell_exec - and assumes you're using Unix/Linux and have shell access -

function dir($directory){
   $files=shell_exec("ls ".$directory);
   return explode("\n",$files);
}

This returns an array with all the files.
This way, you can use modifiers like -t, which shows files in order of modification time ($files=shell_exec("ls -t ".$directory);).  Enough tweaking and you can use it on Windows, though I can't say how since I don't have a Windows server to try it on
asharm4 at ilstu dot edu
07-Oct-2005 04:56
//this is a function I wrote to sort out the contents of the directory date wise for display.

 $content_array = array();

//set current working directory
$dirname = "C:\temp";

//Load Directory Into Array
$handle=opendir($dirname);
$i=0;
while ($file = readdir($handle))
if ($file != "." && $file != "..")
{
       $content_array[$i][0] = $file;
       $content_array[$i][1] = date ("Y m d", filemtime($dirname."/".$file));
       $i++;
}
//close the directory handle
closedir($handle);

//these lines sort the contents of the directory by the date
   foreach($content_array as $res)
       $sortAux[] = $res[1];
   array_multisort($sortAux, SORT_ASC, $content_array);
06-Oct-2005 04:40
This function sorts files by name as strings, but without regard to case.  It also does some handy string formatting of the file size information.

<?
function getFiles($path) {
  
//Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
   //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
   //relative to each other in the order presented by readdir()
  
$files = array();
  
$fileNames = array();
  
$i = 0;
  
   if (
is_dir($path)) {
       if (
$dh = opendir($path)) {
           while ((
$file = readdir($dh)) !== false) {
               if (
$file == "." || $file == "..") continue;
              
$fullpath = $path . "/" . $file;
              
$fkey = strtolower($file);
               while (
array_key_exists($fkey,$fileNames)) $fkey .= " ";
              
$a = stat($fullpath);
              
$files[$fkey]['size'] = $a['size'];
               if (
$a['size'] == 0) $files[$fkey]['sizetext'] = "-";
               else if (
$a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
               else if (
$a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
               else
$files[$fkey]['sizetext'] = $a['size'] . " bytes";
              
$files[$fkey]['name'] = $file;
              
$files[$fkey]['type'] = filetype($fullpath);
              
$fileNames[$i++] = $fkey;
           }
          
closedir($dh);
       } else die (
"Cannot open directory:  $path");
   } else die (
"Path is not a directory:  $path");
  
sort($fileNames,SORT_STRING);
  
$sortedFiles = array();
  
$i = 0;
   foreach(
$fileNames as $f) $sortedFiles[$i++] = $files[$f];
  
   return
$sortedFiles;
}

$files = getFiles("C:");
foreach (
$files as $file) print "$file[name]<br>\n";
?>
Lasse Dalegaard
21-May-2005 07:25
I made a function for finding all files in a specified directory and all subdirectories. It can be quite usefull when searching in alot of files in alot subdirectories. The function returns an array with the path of all the files found.

<?
function getFiles($directory) {
  
// Try to open the directory
  
if($dir = opendir($directory)) {
      
// Create an array for all files found
      
$tmp = Array();

      
// Add the files
      
while($file = readdir($dir)) {
          
// Make sure the file exists
          
if($file != "." && $file != ".." && $file[0] != '.') {
              
// If it's a directiry, list all files within it
              
if(is_dir($directory . "/" . $file)) {
                  
$tmp2 = getFiles($directory . "/" . $file);
                   if(
is_array($tmp2)) {
                      
$tmp = array_merge($tmp, $tmp2);
                   }
               } else {
                  
array_push($tmp, $directory . "/" . $file);
               }
           }
       }

      
// Finish off the function
      
closedir($dir);
       return
$tmp;
   }
}

// Example of use
print_r(getFiles('.')); // This will find all files in the current directory and all subdirectories
?>
brett at medeaproject dot co dot za
11-May-2005 07:02
This is a little script i wrote to generate a home page on my dev box by parsing the contents of my htdocs directory. It is encapsulated in a html table

Arb but useful if you are as lazy as I am ;)
<?
$handle
= opendir("./");

while ((
$file = readdir($handle))!==false) {
  if(
is_dir($file)){
   if(
$file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file;?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

    
}
  }
}
closedir($handle);
$handle = opendir("./");
while ((
$file = readdir($handle))!==false) {
  if(
is_file($file)){
   if(
$file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

    
}
  }
}
closedir($handle);
?>
brett at medeaproject dot co dot za
11-May-2005 07:01
This is a little script i wrote to generate a home page on my dev box by parsing the contents of my htdocs directory. It is encapsulated in a html table

Arb but useful if you are as lazy as I am ;)
<?
$handle
= opendir("./");

while ((
$file = readdir($handle))!==false) {
  if(
is_dir($file)){
   if(
$file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file;?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

    
}
  }
}
closedir($handle);
$handle = opendir("./");
while ((
$file = readdir($handle))!==false) {
  if(
is_file($file)){
   if(
$file != "." && $file != ".."){?>
  <tr>
  <td align="center" bgcolor="FFFFFF"><a href="<?= $file?>"><?php echo ucwords($file)?></a></strong></td>
  </tr>
  <?php

    
}
  }
}
closedir($handle);
?>
iamnotanerd
29-Mar-2005 05:38
Here is a snippet of the code that I created to search for a file..recursively open the directories and search for a match..
<?
function search($target, $directory){
    
   if(
is_dir($directory)){
      
$direc = opendir($directory);
       while(
false !== ($file = readdir($direc))){
          
           if(
$file !="." && $file != ".."){

               if(
is_file($directory."/".$file)){
                   if(
preg_match("/$target/i", $file)){
                                           echo
"<a href=\"$directory/$file\">$file</a><br>";
                                       }
               }else if(
is_dir($directory."/".$file)){
                  
search($target,$directory."/".$file);
                  
               }

           }
       }
      
closedir($direc);
   }

   return ;
}
?>
hendrik dot wermer at gmx dot de
08-Feb-2005 01:06
Here's another version of directory listing, since I had some problems using the examples below. It will display the content of the current directory, sorted by directories and files.
You can also search subdirectories by setting $maxDepth > 0. There's a link to other directories, so you can easily switch to the parent directory or to other directories in the current directory.
Hope it helps!

<?php
// show directory content
function showDir($dir, $i, $maxDepth){
  
$i++;
   if(
$checkDir = opendir($dir)){
      
$cDir = 0;
      
$cFile = 0;
      
// check all files in $dir, add to array listDir or listFile
      
while($file = readdir($checkDir)){
           if(
$file != "." && $file != ".."){
               if(
is_dir($dir . "/" . $file)){
                  
$listDir[$cDir] = $file;
                  
$cDir++;
               }
               else{
                  
$listFile[$cFile] = $file;
                  
$cFile++;
               }
           }
       }
      
      
// show directories
      
if(count($listDir) > 0){
          
sort($listDir);
           for(
$j = 0; $j < count($listDir); $j++){
               echo
"
               <tr>"
;
                  
$spacer = "";
                   for(
$l = 0; $l < $i; $l++) $spacer .= "&emsp;";
                  
// create link
                  
$link = "<a href=\"" . $_SERVER["PHP_SELF"] . "?dir=" . $dir . "/" . $listDir[$j] . "\">$listDir[$j]</a>";
                   echo
"<td>" . $spacer . $link . "</td>
               </tr>"
;
              
// list all subdirectories up to maxDepth
              
if($i < $maxDepth) showDir($dir . "/" . $listDir[$j], $i, $maxDepth);
           }
       }
      
      
// show files
      
if(count($listFile) > 0){
          
sort($listFile);
           for(
$k = 0; $k < count($listFile); $k++){
              
$spacer = "";
               for(
$l = 0; $l < $i; $l++) $spacer .= "&emsp;";
               echo
"
               <tr>
                   <td>"
. $spacer . $listFile[$k] . "</td>
               </tr>"
;   
           }
       }       
      
closedir($checkDir);
   }
}

if(
$_GET["dir"] == "" || !is_dir($_GET["dir"])) $dir = getcwd();
else
$dir = $_GET["dir"];
// replace backslashes, not necessary, but better to look at
$dir = str_replace("\\", "/", $dir);

// show parent path
$pDir = pathinfo($dir);
$parentDir