readdir

(PHP 3, PHP 4, PHP 5)

readdir -- 从目录句柄中读取条目

说明

string readdir ( resource dir_handle )

返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。

参数

dir_handle

目录句柄的 resource,之前由 opendir() 打开

返回值

成功则返回文件名,失败返回 FALSE

范例

例子 1. 列出目录中的所有文件

请留意下面例子中检查 readdir() 返回值的风格。这里明确地测试返回值是否全等于(值和类型都相同――更多信息参见比较运算符FALSE,否则任何目录项的名称求值为 FALSE 的都会导致循环停止(例如一个目录名为“0”)。

<?php
// 注意在 4.0.0-RC2 之前不存在 !== 运算符

if ($handle = opendir('/path/to/files')) {
    echo
"Directory handle: $handle\n";
    echo
"Files:\n";

    
/* 这是正确地遍历目录方法 */
    
while (false !== ($file = readdir($handle))) {
        echo
"$file\n";
    }

    
/* 这是错误地遍历目录的方法 */
    
while ($file = readdir($handle)) {
        echo
"$file\n";
    }

    
closedir($handle);
}
?>

例子 2. 列出当前目录的所有文件并去掉 ...

<?php
if ($handle = opendir('.')) {
    while (
false !== ($file = readdir($handle))) {
        if (
$file != "." && $file != "..") {
            echo
"$file\n";
        }
    }
    
closedir($handle);
}
?>


add a note add a note User Contributed Notes
repley at freemail dot it
23-May-2006 10:27
Upgrade of davidstummer's listImages function: now with order by and sorting direction (like SQL ORDER BY clause).

<?php
//listImages(string path, string sort-by name | width | height | size, int sorting order flags SORT_ASC | SORT_DESC)
function listImages($dirname, $sortby, $sortdir) {

$ext = array("jpg", "png", "jpeg", "gif");
$files = array();
   if(
$handle = opendir($dirname)) {
       while(
false !== ($file = readdir($handle))){
           for(
$i=0;$i<sizeof($ext);$i++){
               if(
stristr($file, ".".$ext[$i])){ //NOT case sensitive: OK with JpeG, JPG, ecc.
                  
$imgdata = getimagesize($dirname . "/" . $file);
                  
$filesize = filesize($dirname . "/" . $file);
                  
//Some formats may contain no image or may contain multiple images.
                   //In these cases, getimagesize() might not be able to properly determine the image size.
                   //getimagesize() will return zero for width and height in these cases.
                  
if($imgdata[0] && $imgdata[1] && $filesize){
                      
$files[] = array(
                                      
"name" => $file,
                                      
"width" => $imgdata[0],
                                      
"height" => $imgdata[1],
                                      
"size" => $filesize
                                
);
                   }
               }
           }
       }
  
closedir($handle);
   }
 
  
//obtain an array of columns
  
foreach ($files as $key => $row) {
      
$name[$key]  = $row['name'];
      
$width[$key] = $row['width'];
      
$height[$key] = $row['height'];
      
$size[$key] = $row['size'];
   }
 
return
array_multisort($$sortby, $sortdir, $files) ? $files : false;
}
//end listImages

//start test
$sortby = "width"; // sort-by column; accepted values: name OR width OR height OR size
$path = "path"; // path to folder
$sortdir = SORT_ASC; // sorting order flags; accepted values: SORT_ASC or SORT_DESC

$files = listImages($path, $sortby, $sortdir);
foreach (
$files as $file){
   echo
'name = <strong>' . $file['name'] . '</strong> width = <strong>' . $file['width'] . '</strong> height = <strong>' . $file['height'] . '</strong> size = <strong>' . $file['size'] . '</strong><br />';
}
//end test
?>

Repley.
repley at freemail dot it
19-May-2006 07:53
BugFix of davidstummer at yahoo dot co dot uk listImages() function:

<?php
function listImages($dirname=".") {
  
$ext = array("jpg", "png", "jpeg", "gif");
  
$files = array();
   if(
$handle = opendir($dirname)) {
       while(
false !== ($file = readdir($handle)))
           for(
$i=0;$i<sizeof($ext);$i++)
               if(
stristr($file, ".".$ext[$i])) //NOT case sensitive: OK with JpeG, JPG, ecc.
                  
$files[] = $file;
      
closedir($handle);
   }
   return(
$files);
}
?>
Thanks to all.

Repley
vorozhko at gmail dot com
19-Apr-2006 04:39
Here is my recursive read dir function, what read dir by mask.
[php]
function ls($dir, $mask /*.php$|.txt$*/)
{
       static $i = 0;
       $files = Array();
       $d = opendir($dir);
       while ($file = readdir($d))
       {
               if ($file == '.' || $file == '..' || eregi($mask, $file) ) continue;
               if (is_dir($dir.'/'.$file))
               {
                       $files += ls($dir.'/'.$file, $mask);
                       continue;
               }
               $files[$i++] = $dir.'/'.$file;
       }
       return $files;
}
$f = ls('E:/www/mymoney/lsdu', ".php$" /*no spaces*/);
[/php]
phathead17 at yahoo dot com
10-Apr-2006 02:14
moogman,

While using your excellent readdirsort function, php complains that the next element in the $items array could not be found.

Instead of:
   if ($items[$last_read_item] == false)

Just use:
   if (!isset($items[$last_read_item]) || $items[$last_read_item] == false)
anonimo
29-Mar-2006 08:06
----------------------
To Marijan Greguric
----------------------

In your script there is a little bug with folders with same name but different path :

i think that is correct to use this id

$id="$path$file";

and not

$id="$file";

bye

L
moogman
23-Feb-2006 07:04
Took cart at kolix dot de's wrapper and changed it into a simple readdir wrapper that does the same, but puts directories first and sorts. Hope it's useful :)

function readdirsort($dir) {
       /* Funktastic readdir wrapper. Puts directories first and sorts. */
       static $not_first_run, $last_read_item=0, $items;

       if (!$not_first_run) {
               $not_first_run = true;
               while (false !== ($file = readdir($dir))) {
                       if (is_dir("$file"))
                               $dirs[] = $file;
                       else
                               $files[] = $file;
               }

               natcasesort($dirs);
               natcasesort($files);

               $items = array_merge($dirs, $files);
       }

       if ($items[$last_read_item] == false)
               return false;
       else
               return $items[$last_read_item++];
}
imran at imranaziz dot net
19-Feb-2006 05:02
Based on tips above, I made this function that displays all php files in your whole website, like a tree. It also displays which directory they're in.

     $dir = $_SERVER['DOCUMENT_ROOT'];
     $shell_command = `find $dir -depth -type f -print`;
     $files = explode ("\n", $shell_command);
     foreach ($files as $value)
     {
         $fileInfo = pathinfo($value);
         $extension = $fileInfo["extension"];
         if ($extension == "php")
         {
           $cur_dir = str_replace($_SERVER['DOCUMENT_ROOT'], "", dirname($value));
           if ($cur_dir != $old_dir)
           {
               echo "<p><b>" . $cur_dir . "</b></p>";
               $old_dir = $cur_dir;
           }
           echo $cur_dir . "/" . basename($value) . "<BR>";
         }
     }

You can change it to take input of certain directory or files of certain, or no extension.
cart at kolix dot de
01-Feb-2006 03:53
*updated version

Here is my recursive read_dir function. It sorts directories and files alphabetically.

<?php
function read_dir($dir) {
  
$path = opendir($dir);
   while (
false !== ($file = readdir($path))) {
       if(
$file!="." && $file!="..") {
           if(
is_file($dir."/".$file))
              
$files[]=$file;
           else
              
$dirs[]=$dir."/".$file;           
       }
   }
   if(
$dirs) {
      
natcasesort($dirs);
       foreach(
$dirs as $dir) {
           echo
$dir;
          
read_dir($dir);
       }
   }
   if(
$files) {
      
natcasesort($files);
       foreach (
$files as $file)
           echo
$file
  
}
  
closedir($path);
}
?>

Start with:
<?php
$path
="path/to/your/dir";
read_dir($path);
?>
Marijan Greguric
31-Jan-2006 01:38
Example directory tree with javascript
<script>
function pokazi(dir){
         alert(dir);
         x=document.getElementById(dir);
         if(x.style.display == "none"){
               x.style.display = "";
         }else{
               x.style.display = "none";
                 }

}
</script>
</head>

<body>

<?php
$path
= "../../upload/";
if (
$handle = opendir($path)) {
   while (
false !== ($file = readdir($handle))) {
       if (
$file != "." && $file != "..") {
           if(
is_dir("$path".$file)){
                 echo
"<div style=\"padding-left: 2px; margin: 0px; border: 1px solid #000000;\"  >";
                 echo
"|-<b><a href=\"#\" onClick=pokazi(\"$file\")>$file</a></b><br />\n";
                
$id="$file";

                
dirT("$path$file/",$id);

           }else{
                 echo
"$file<br />\n";
                 }
       }

   }
   echo
"</div>";
  
closedir($handle);
}
function
dirT($path,$id){
   echo
"<div style=\"padding-left: 2px; margin: 2px; border: 1px solid #000000; display:none \" id=\"$id\">";
           if (
$handle = opendir($path)) {
               while (
false !== ($file = readdir($handle))) {
                       if (
$file != "." && $file != "..") {
                           if(
is_dir("$path".$file)){
                             echo
"<div style=\"padding-left: 10px; margin: 2px; border: 1px solid #000000; \" >";
                             echo
"|-<a href=\"#\" onClick=pokazi(\"$file\")>$file</a><br />\n";
                            
$id="$file";
                            
dirT("$path$file/",$id);
                           }else{
                             echo
"&nbsp;--$file<br />\n";
                           }
               }
           }
           echo
"</div>";
          
closedir($handle);
   }
   echo
"</div>";
}

?>
larry11 at onegentleman dot biz
21-Jan-2006 02:23
After hours of work I found an error in the sort routine sumitted. The correction lies in the fact you need $path.$file to diffirentiate from [dir] or [file] in the routines

$path = "music/Holly Dunn/";
   $dh = opendir($path);

   while (false !== ($file=readdir($dh)))
   {
     if (substr($file,0,1)!=".")
     {
         if (is_dir($path.$file))
        
         $dirs[]=$file.'/'; 
         else
           $files[]=$file; 
     }
   }
   @closedir($dh);

   if ($files)
     natcasesort($files);
   if ($dirs)
     natcasesort($dirs);

   $files=array_merge($dirs,$files);

   foreach ($files as $file)
     echo "<a href=$file>$file</a><br />";

   ?>
info [AT] thijsbaars [DOT] NL
29-Dec-2005 03:39
wrote this piece. I use it to validate my $_GET variables.

It firsts gets the variable $page, cheks if that variable is assinged (on the main index, it is not).
if it is assinged, it checks if it equals one of the found directory's, and then i assigns the variable definatly.

this is a rather secure way of validating the $_GET variable, which on my site should only have the name of one of my directory's.
 
<?php
$page
= $_GET['a'];

if (
$page != "" || !empty($page))
{
  
$handle=opendir('albums');

   while (
false!==($file = readdir($handle)))
   {
       if (
substr($file,0,1)!=".")            //do not look up files or directory's which start with a dot
      
{
           if(!
eregi("thumb",$file))        // all files and dir's containign the word thumb are filtred out
          
{
              
$path = "albums/" . $file;   
               if(
is_dir($path))            // only directory's will get listed
              
{
                   if(
$page != $file) die("wrong argument! only a existing album may be set"); // validates input
                      
else
                       {
                      
$page = "albums/" . $page;
                      
$thumb = $page . thumb;
                       }
               }
           }
       }
   }
  
closedir($handle);
}
doom at inet dot ua
16-Dec-2005 07:10
How i make my directory tree for print (you can make array)

<?php

$First_Dir
= "./my_big_dir";

read_dir($First_Dir);

/**** functions part ****/

function read_dir($name_subdir)
{
$dh = opendir($name_subdir);
while(
gettype($file = readdir($dh))!=boolean)
   {
   if (
$file != '..')
   if (
$file != '.')
         {
        
$current_element = $name_subdir."/".$file;
         if(
is_dir($current_element))
             {
             echo
$current_element."<br>";
            
read_dir($current_element);
             }
         }
   }
closedir($dh);
}
?>

Best free :-)
Absynthe
30-Nov-2005 02:18
This is a function to read all the directories and subdirectories of a folder. It returns an array with all the paths.

<?PHP

$root
= "root";

function
arborescence($root)
{
  
  
$folders  = array();
  
$path    = "$root";
  
$i    = 0;

  
// Vrification de l'ouverture du dossier
  
if ($handle = opendir("./".$path))
   {
      
// Lecture du dossier
      
while ( false !== ($file = readdir($handle)) )
       {
           if (
filetype($path."/".$file) == 'dir')
           {
               if (
$file != '..' && $file != '.' && $file != '' && (substr($file,0,1) != '.'))
               {
                  
$folders[$i] = "./".$path."/".$file;
                  
$i++;
               }
           }
       }
      
closedir($handle);
      
      
// Recherche de tous les sous dossiers pour chaque dossiers
      
for ( $u = 0; $u < $i; $u++ )
       {
           if (
$handle = opendir($folders[$u]))
           {
              
// Lecture du dossier
              
while ( false !== ($file = readdir($handle)) )
               {
                   if (
filetype("./".$folders[$u]."/".$file) == 'dir')
                   {
                       if (
$file != '..' && $file != '.' && $file != '' && (substr($file,0,1) != '.'))
                       {
                          
$folders[$i] = $folders[$u]."/".$file;
                          
$i++;
                       }
                   }
               }
              
closedir($handle);
           }
       }
   }
return
$folders;
}

?>
Martin dot Grossberger at andtek dot com
25-Nov-2005 10:39
to ES:
i believe you are mistaken. readdir() returns a string (the filename), not an array

therefor, the open_dir function should be like this:

function open_dir($dir) {
  $this->dir = $dir;
  $handle = opendir($this->dir);
  if($handle) {
   while(false !== ($file = readdir($handle)) {
     if($file != "." && $file != "..") {
       $files[] = $file;
     }
   }
   sort($files);
   foreach($files as $file) {
     echo $file."<br>";
   }
  }
}
ES
25-Nov-2005 07:58
A simple class to read a dir, and display the files. And will automatically sort the files Alphabetically. Very simple indeed. But thought I'd share (one of my first classes aswell) :)

<?php

class list_dir
{
  var
$dir;

  function
open_dir($dir)
  {
  
$handle = opendir($this->dir);
   if(
$handle)
   {
     while(
false !== ($files = readdir($this->dir)))
     {
       if(
$files != "." && $files != "..")
       {
        
sort($files);
         foreach(
$files as $file)
         {
           echo
$file."<br>";
         }
       }
     }
   }
  }
  function
close_dir()
  {
  
closedir($this->dir);
  }
}
?>

Usage:
<?php

$list
= new list_dir;
$list->open_dir("/path/to/directory/");
$list->close_dir();

?>
24-Sep-2005 05:31
To beanz at gangstersonline dot co dot uk, just a little optimization tip.

You have make a lot of eregi calls in a sequence of elseif statements.  That means that for a worst case, you'll be making 8 eregi calls per iteration.  Instead of using a bunch of conditional eregi() calls (which is much slower compared to preg_match or strpos), you could do the following:

<?php
if ($i)
//create a mapping array
$ext_map = array('exe' => 'exe', 'bmp' => 'image1', etc....)
foreach(
$tab as $rep) {
 
//use one preg_match to grab the extention
 
if (preg_match('/\.([a-z]+)$/', $rep, $matches) {
    
$ext = $ext_map[$matches[1]];
  } else {
    
$ext = 'text';
  }
 
//rest of code...
}
?>

So instead of a worst case of n eregi calls per iteration, you're guaranteed only one preg_match per call.  Or possibly even faster than preg_match:

$ext = $ext_map[substr($rep, strrpos($rep, '.'))];
beanz at gangstersonline dot co dot uk
19-Sep-2005 11:43
A little script I made for my home page on local host. It displays the contents of the folder in which the script is placed, and adds some images in a folder supplied (which is elminated from the file list)

<?PHP
  $list_ignore
= array ('.','..','images','Thumbs.db','index.php'); // Windows server, so thumbs.db shows up :P
 
$handle=opendir(".");
 
$dirs=array();
 
$files=array();
 
$i = 0;
  while (
false !== ($file = readdir($handle))) {
   if (!
in_array($file,$list_ignore)) {
     if(!
eregi("([.]bak)",$file)) { // ignore backup files
      
if(is_dir($file)) {
        
$dirs[]=$file;
       } else {
        
$files[]=$file;
       }
      
$i++;
     }
   }
  }
 
closedir($handle);
 
$tab=array_merge($dirs,$files);
  if (
$i) {
   foreach (
$tab as $rep) {
     if(
eregi("[.]exe", $rep)) {
      
$ext="exe";
     } elseif(
eregi("[.]php", $rep)) {
      
$ext="php";
     } elseif(
eregi("[.]bmp", $rep)) {
      
$ext="image2";
     } elseif(
eregi("[.]doc", $rep)) {
      
$ext="word";
     } elseif(
eregi("[.]xls", $rep)) {
      
$ext="excel";
     } elseif(
eregi("([.]zip)|([.]rar)", $rep)) {
      
$ext="archive";
     } elseif(
eregi("([.]gif)|([.]jpg)|([.]jpeg)|([.]png)", $rep)) {
      
$ext="image";
     } elseif(
eregi("([.]html)|([.]htm)", $rep)) {
      
$ext="firefox";
     } elseif(
$rep[folder]==true) {
      
$ext="folder";
     } else {
      
$ext="text";
     }
     echo (
'<a href="'.$rep.'"><img src="images/'.$ext.'.bmp" border="0"> '.$rep.'</a><br>');
   }
  } else {
   echo
"No files";
  }
?>
anonymous at anonymous dot org
09-Aug-2005 09:11
My simple function for clean up .svn directory
It doesn't recursive, but exec rmdir :P

function clean_svn( $stack )
{
  $dir_list = array();
  $rm_list = array();

  // translate to real path
  $stack = realpath( $stack );

  // Initial dir_list with $stack
  array_push( $dir_list, $stack );

  while( $current_dir = array_pop( $dir_list ) )
  {
   $search = $current_dir . "\\" . "{*,.svn}";

   foreach( glob( $search, GLOB_ONLYDIR | GLOB_BRACE ) as $name )
   {
     if( ereg( '\.svn$', $name ) )
       array_push( $rm_list, $name );
     else
       array_push( $dir_list, $name );
   }
  }

  // remove directory
  foreach( $rm_list as $name )
  {
   exec( "rmdir /S /Q $name" );
  }
}
Basis - basis.klown-network.com
04-Aug-2005 04:11
Alex's example was really good except for just one small part that was keeping it from displaying directories above files in alphabetical order (His has makes the directories and files mixed)

I changed 'if (is_dir($path.$file))' to 'if (is_dir($file))' and it works perfectly now.  Here's the whole block.

<code>
$path = $_SERVER[DOCUMENT_ROOT];
   $dh = @opendir($path);

   while (false !== ($file=@readdir($dh)))
   {
     if (substr($file,0,1)!=".")
     {
         if (is_dir($file))
           $dirs[]=$file.'/'; 
         else
           $files[]=$file; 
     }
   }
   @closedir($dh);

   if ($files)
     natcasesort($files);
   if ($dirs)
     natcasesort($dirs);

   $files=array_merge($dirs,$files);

   foreach ($files as $file)
     echo "<a href=$file>$file</a><br />";
</code>
Alex M
28-Jun-2005 11:37
A shorter and simpler version of twista no[at]$pam rocards $pam[dot]no de
code to first display all folders sorted, and THEN all files sorted. Just like windows.

<?php
   $path
= $_SERVER[DOCUMENT_ROOT]."/old/";
  
$dh = @opendir($path);

   while (
false !== ($file=@readdir($dh)))
   {
     if (
substr($file,0,1)!="."#skip anything that starts with a '.'
    
{                            #i.e.:('.', '..', or any hidden file)
        
if (is_dir($path.$file))
          
$dirs[]=$file.'/'#put directories into dirs[] and append a '/' to differentiate
        
else
          
$files[]=$file#everything else goes into files[]
    
}
   }
   @
closedir($dh);

   if (
$files)
    
natcasesort($files); #natural case insensitive sort
  
if ($dirs)
    
natcasesort($dirs);

  
$files=array_merge($dirs,$files);  #merge dirs[] and files[] into files with dirs first

  
foreach ($files as $file#that's all folks, display sorted all folders and files
    
echo "$file<br>\n";
?>
matthew dot panetta at gmail dot com
16-May-2005 07:44
Here is a simple directory walker class that does not use recursion.
<?
class DirWalker {
   function
go ($dir) {
      
$dirList[] = $dir;
       while ( (
$currDir = array_pop($dirList)) !== NULL ) {
          
$dir = opendir($currDir);
           while((
false!==($file=readdir($dir)))) {
               if(
$file =="." || $file == "..") {
                   continue;
               }
              
              
$fullName = $currDir . DIRECTORY_SEPARATOR . $file;
              
               if (
is_dir ( $fullName ) ) {
                  
array_push ( $dirList, $fullName );
                   continue;
               }
              
              
$this->processFile ($file, $currDir);
           }
          
closedir($dir);
       }
   }
  
   function
processFile ( $file, $dir ) {
       print (
"DirWalker::processFile => $file, $dir\n");
   }
}
?>
twista no[at]$pam rocards $pam[dot]no de
12-Apr-2005 05:18
I used nagash's script from below fo myself, and enhanced it.
It will now first display all folders sorted, and THEN all files sorted. Just like windows :-)

There is also a small function for hiding secret files.

Just set $rootdir to 1 in the root dir, and leave it 0 in all subdirs.

<?

$the_file_array
= Array();
$the_folder_array = Array();
$handle = opendir('./');

while (
false !== ($file = readdir($handle))) {
   if (
$file != ".") {
   if (
filetype($file) == "file") { $the_file_array[] = $file; } else if (filetype($file) == "dir") {$the_folder_array[] = $file; }
   }
}

closedir($handle);
sort ($the_file_array);
reset ($the_file_array);
sort ($the_folder_array);
reset ($the_folder_array);

while (list (
$key, $val) = each ($the_folder_array)) {
   if ((
$val != ".") && (!fnmatch("*.php*", $val))) {
       if ((
fnmatch("~*", $val)) || (fnmatch("~some_thing", $val))) {
          
// CASE: An outcommented file. - Syn: "~<filename>" - Exp: "~nottobeseen.txt"
          
echo "** SECRET FILE **<br>";
       }else{
           if (
$val == "..") {
               if (
$rootdir == "1") {
                  
// CASE: Don't show the way upward if this is the root directory.
                   // Root Directory, do nothing.
              
}else{
                  
// CASE: Show the ".." to go back if this is NOT the root directory.
                  
echo '<a href="'.$val.'/">/'.$val.'/</a><br>';
               }
           }else{
              
// CASE: All normal folders. No ".." and no ".".
              
echo '<a href="'.$val.'/">/'.$val.'/</a><br>';
           }
       }
   }
}

while (list (
$key, $val) = each ($the_file_array)) {
   if ((
$val != ".") && (!fnmatch("*.php*", $val))) {
       if ((
fnmatch("*~~*", $val)) || (fnmatch("~cheat_sux^hi", $val))) {
          
// CASE: An outcommented file. - Syn: "~<filename>" - Exp: "~nottobeseen.txt"
          
echo "** SECRET FILE **<br>";
       }else{
               echo
'<a href="'.$val.'">'.$val.'</a><br>';
           }
   }
}

?>
steve at stevedix dot de
15-Feb-2005 05:12
IT IS VITALLY IMPORTANT that when using opendir and then scanning with readdir, that you test opendir to see if it has returned a valid pointer.

The following code does not :
<?php

$dir
= opendir($mydir);
while((
false!==($file=readdir($dir))))
   if(
$file!="." and $file !="..")
      
unlink($mydir.'/'.$file);
closedir($dir);

?>
if $mydir is not a valid directory resource (for example, the directory in question has been deleted), then the code will loop infinitely.  Of course, it'll stop eventually if you have set a max execution time, but in the meantime it will visibly slow the server.
Anton Fors-Hurdn <atombomben at telia dot com>
21-Dec-2004 05:10
My download function:

<?
function download($dir) {

   if (isset(
$_GET['download'])) {

      
header("Content-Type: octet/stream");
      
header("Content-Disposition: attachment; filename=" . basename($_GET['download']));

       echo
file_get_contents($_GET['download']);

   } else {

     if (
$open = opendir($dir)) {
         while (
false !== ($file = readdir($open))) {
               if (
$file != "." && $file != "..") {
                   if (!
is_dir($dir . $file)) {

                         echo
"< <a href=\"?download=" . $dir . $file . "\">" . $file . "</a><br />\n";

                   } else {

                         echo
"> " . $file . "<br />\n";
                         echo
"<div style=\"padding-left: 15px;\">";
                        
download($dir . $file . "/");
                         echo
"</div>";
                   }
               }
           }
                
closedir($open);
     }
   }
}
?>
boorick[at]utl[dot]ru
16-Dec-2004 06:07
Simple script which counts directories and files in the set directory.

$path = '/path/to/dir'
if ($handle = opendir($path)) {
   while (false !== ($file = readdir($handle))) {
       if ($file != "." && $file != "..") {
           $fName = $file;
           $file = $path.'/'.$file;
           if(is_file($file)) $numfile++;
           if(is_dir($file))  $numdir++;
       };
   };
   closedir($handle);
};
echo $numfiles.' files in a directory';
echo $numdir.' subdirectory in directory';
BY626
07-Dec-2004 06:15
here is a simple directory navigating script i created. files and directories are links and it displays the current directory and the path relative to the file the script is in. it also has a nifty 'up one level' link.
------

<?php
   $path
= $_GET['path'];
   if(!isset(
$path))
   {
      
$path = ".";
   }

   if (
$handle = opendir($path))
   {
      
$curDir = substr($path, (strrpos(dirname($path."/."),"/")+1));
       print
"current directory: ".$curDir."<br>************************<br>";   
       print
"Path: ".dirname($path."/.")."<br>************************<br>";

       while (
false !== ($file = readdir($handle)))
       {
           if (
$file != "." && $file != "..")
           {
              
$fName = $file;
              
$file = $path.'/'.$file;
               if(
is_file($file))
               {
                   print
"[F]&nbsp;&nbsp;<a href='".$file."'>".$fName."</a>&nbsp;&nbsp;&nbsp; ".filesize($file)." bytes<br>";
               }
               if(
is_dir($file))

               {
                   print
"[D]&nbsp;&nbsp;<a href='ex2.php?path=$file'>$fName</a><br>";
               }
           }
       }
      
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
       print
"[^]&nbsp;&nbsp;<a href='ex2.php?path=$up'>up one level</a><br>";

      
closedir($handle);
   }
?>

------ sample output ------

current directory: kate
************************
Path: ./kate
************************
[F]  xyz_file.txt  13005 bytes
[F]  mno_file.txt  26327 bytes
[F]  abc_file.txt  8640 bytes
[D]  k2
[^]  up one level
Jason Wong
13-Nov-2004 06:20
Everyone seems to be using recursion for trawling through subdirectories. Here's a function that does not use recursion.

<?php
  
function list_directory($dir) {
      
$file_list = '';
      
$stack[] = $dir;
       while (
$stack) {
          
$current_dir = array_pop($stack);
           if (
$dh = opendir($current_dir)) {
               while ((
$file = readdir($dh)) !== false) {
                   if (
$file !== '.' AND $file !== '..') {
                      
$current_file = "{$current_dir}/{$file}";
                       if (
is_file($current_file)) {
                          
$file_list[] = "{$current_dir}/{$file}";
                       } elseif (
is_dir($current_file)) {
                          
$stack[] = $current_file;
                       }
                   }
               }
           }
       }
       return
$file_list;
   }
?>

I also did a rudimentary benchmark against Rick's function (no reason in particular why I chose Rick's, it was just the latest) and the result is that using recursion results in about 50% longer execution time.

Details of benchmark:
Directory contains 64 subdirectories and about 117,000 files. Each function was executed 100 times in a for-loop and the average time per iteration was calculated. The result is 3.77 seconds for the non-recursive function and 5.65 seconds for the recursive function.
Rick at Webfanaat dot nl
29-Sep-2004 06:47
Yet another recursive directory lister :P
Why did I create it?
I like to keep things small, and it seems like all the scripts around here are a lot bigger and more complex while they produce the same (or nearly the same) output.

This one creates a multidimensional array with the folders as associative array and the files as values.
It puts the name of the folders and files in it, not the complete path (I find that annoying but its easy to change that if you prefer it with the path).

And I used a for loop instead of a while loop like everyone around here does.
Why?
1. I just like for loops.
2. Everyone else uses a while loop.

<?php
function ls($dir){
  
$handle = opendir($dir);
   for(;(
false !== ($readdir = readdir($handle)));){
       if(
$readdir != '.' && $readdir != '..'){
          
$path = $dir.'/'.$readdir;
           if(
is_dir($path))    $output[$readdir] = ls($path);
           if(
is_file($path))    $output[] = $readdir;
       }
   }
   return isset(
$output)?$output:false;
  
closedir($handle);
}

print_r(ls('.'));
?>

PS: if you don't need the files in it then you can just comment out the "if(is_file....." part.
nagash at trumna dot pl
06-Jun-2004 01:11
Simplified recursive file listing (in one directory), with links to the files.

<?
$the_array
= Array();
$handle = opendir('prace/.');
while (
false !== ($file = readdir($handle))) {
   if (
$file != "." && $file != "..") {
  
$the_array[] = $file;
   }
}
closedir($handle);
sort ($the_array);
reset ($the_array);
while (list (
$key, $val) = each ($the_array)) {
   echo
"<a href=prace.php?id=$val>$val</a><br>";
}
?>

I'm not sure, if you were talking about that, but anyway I think somebody might find it usefull :-)
phpuser at php dot net
04-Jun-2004 11:28
Simplified recursive directory listing. Returns FolderListing object which contains an array with all the directories and files.

<?php

class FolderListing {
   var
$newarr = array();

   function
loop($stack) {
       if(
count($stack) > 0) {
          
$arr = array();
           foreach(
$stack as $key => $value) {
              
array_push($this->newarr, $stack[$key]);
               if (
$dir = @opendir($stack[$key])) {
                   while ((
$file = readdir($dir)) !== false) {
                       if ((
$file != '.') && ($file != '..')) {
                          
array_push($arr, $stack