PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

rewinddir> <opendir
Last updated: Fri, 26 Sep 2008

view this page in

readdir

(PHP 4, PHP 5)

readdirПолучить элемент каталога по его дескриптору

Описание

string readdir ( resource $dir_handle )

Возвращает имя следующего по порядку элемента каталога. Имена элементов возвращаются в порядке, зависящем от файловой системы.

Обратите внимание на способ проверки значения, возвращаемого функцией readdir() в приведенном ниже примере. В этом примере осуществляется проверка значения на идентичность (выражения идентичны, когда они равны и являются значениями одного типа - за более подробной информацией обратитесь к главе Операторы сравнения) значению FALSE, поскольку в ином случае, любой элемент каталога, чье имя может быть выражено как FALSE, остановит цикл (например, элемент с именем "0").

Пример #1 Вывести список всех файлов в каталоге

<?php
// Обратите внимание, что оператор !== не существовал до версии 4.0.0-RC2

if ($handle opendir('/path/to/files')) {
    echo 
"Дескриптор каталога: $handle\n";
    echo 
"Файлы:\n";

    
/* Именно этот способ чтения элементов каталога является правильным. */
    
while (false !== ($file readdir($handle))) { 
        echo 
"$file\n";
    }

    
/* Этот способ НЕВЕРЕН. */
    
while ($file readdir($handle)) { 
        echo 
"$file\n";
    }

    
closedir($handle); 
}
?>

Обратите внимание, что функция readdir() также возвращает элементы с именами . и ... Если вы не хотите получать эти значения, просто отбрасывайте их:

Пример #2 Получить список файлов в текущем каталоге и отбросить элементы с именами . и ..

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

См.также описания функций is_dir() и glob().



rewinddir> <opendir
Last updated: Fri, 26 Sep 2008
 
add a note add a note User Contributed Notes
readdir
Anonymous
30-Sep-2008 10:09
@mesyash_one at wp dot pl

Don´t use
<?php
$fileChunks
= explode(".", $file);
$ext= $fileChunks[1];
?>

It will create a notice if there is a file without extension. And if theres a file with 2 dots the result will be wrong.

Better use
<?php
$fileChunks
= array_reverse(explode(".", $file));
$ext= $fileChunks[0];
?>
and check for files without extension.
mesyash_one at wp dot pl
27-Sep-2008 02:25
<?php
 
//getting all files of desired extension from the dir using explode

 
$desired_extension = 'pdf'; //extension we're looking for
 
$dirname = "uploads/";
 
$dir = opendir($dirname);

  while(
false != ($file = readdir($dir)))
  {
    if((
$file != ".") and ($file != ".."))
    {
     
$fileChunks = explode(".", $file);
      if(
$fileChunks[1] == $desired_extension) //interested in second chunk only
     
{      
        echo
'a href="uploads/'.$file.'" target="_blank"> '.$file.'</a></br>';
      }
    }
  }
 
closedir($dir);
?>
MetaNull
11-Jul-2008 08:20
A simple directory browser... that handles the windows charset in filenames (it should work for every iso-8859-1 characters).
<?php
 $basepath
= realpath("./pub/");  // Root directory
 
$path = realpath($basepath.$_GET["path"]);  // Requested  path
$relativepath = "./".substr_replace( $path, "", 0, strlen( $basepath ) );
 if(
"/" == substr( $relativepath, -1 )) {  // Remove the trailing slash
 
$relativepath = substr( $relativepath, 0, -1 );
 }

$dh = opendir( $path );
  while(
false !== ($file = readdir( $dh ))) {
   if(
"." == $file) {continue;}
  
// converts the filename to utf8
  
$file_utf8 = iconv( "iso-8859-1", "utf-8", $file );
  
// encode the path ('path' part: already utf8; 'filename' part: still iso-8859-1)
  
$link = str_replace( "%2F", "/", rawurlencode( "{$relativepath}/" )) . rawurlencode( utf8_decode( "{$file_utf8}" ));
   if(
is_dir( "{$path}/{$file}" )) {
    echo
"<a href=\"?path={$link}&amp;\">{$file_utf8}</a><br/>"
  
} else {
    echo
"<a href=\"{$link}&amp;\">{$file_utf8}</a><br/>"
  
}
  }
 }
 
?>
Kim Christensen
05-May-2008 05:14
Handy little function that returns the number of files (not directories) that exists under a directory.
Choose if you want the function to recurse through sub-directories with the second parameter -
the default mode (false) is just to count the files directly under the supplied path.

<?php

 
/**
   * Return the number of files that resides under a directory.
   *
   * @return integer
   * @param    string (required)   The directory you want to start in
   * @param    boolean (optional)  Recursive counting. Default to FALSE.
   * @param    integer (optional)  Initial value of file count
   */ 

 
function num_files($dir, $recursive=false, $counter=0) {
    static
$counter;
    if(
is_dir($dir)) {
      if(
$dh = opendir($dir)) {
        while((
$file = readdir($dh)) !== false) {
          if(
$file != "." && $file != "..") {
             
$counter = (is_dir($dir."/".$file)) ? num_files($dir."/".$file, $recursive, $counter) : $counter+1;
          }
        }
       
closedir($dh);
      }
    }
    return
$counter;
  }

 
// Usage:
 
$nfiles = num_files("/home/kchr", true); // count all files that resides under /home/kchr, including subdirs
 
$nfiles = num_files("/tmp"); // count the files directly under /tmp

?>
info at agentur-obermaier dot de
15-Apr-2008 01:13
This is a nice quick full dir read - sorry for my bad english ;)

function ReadDirs($dir,$em){
    if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && $file != "Thumb.db") {
            if(is_dir($dir.$file)){
                echo $em."&raquo; ".$file.'<br>';
                ReadDirs($dir.$file."/",$em."&nbsp;&nbsp;");
            }
        }
    }
    closedir($handle);
}
}
dbzfanatic_1 at hotmail dot com
18-Mar-2008 06:03
Here's an easy way to output the contents as a list of download links.

<?php
$count
= 0;
if (
$handle = opendir('.')) {
    while (
false !== ($file = readdir($handle))) {
        if (
$file != "." && $file != "..") {$count++;
            print(
"<a href=\"".$file."\">".$file."</a><br />\n");
        }
    }
echo
'<br /><br /><a href="..">Return</a>';
   
closedir($handle);
}
?>

and simply use $count to list the overall number of files.
singh206 at gmail dot com
15-Nov-2007 10:15
Oops, made a few syntactical errors in the last example of getting only the final directory paths from a root dir.  PHP 4 OO.

    var $rootDir = '/SOME DIRECTORY';
   
    print_r($this->getFinalDirs($this->rootDir));   
   
    function getFinalDirs($root)
    {
        return $this->getNext($root);
    }
   
    function getNext($path)
    {
        static $dirs = array();
        $handle = opendir($path);
        if($handle)
        {
            while (false!==($dir=readdir($handle)))
            {
                if ($dir!='.'&&$dir!='..'&& $dir!='.DS_Store')
                {
                    if(is_dir($path.'/'.$dir))
                    {
                        $this->getNext($path.'/'.$dir);
                    } else
                    {
                        array_push($dirs, $path);
                        break;
                    }
                }
            }
        }
        return $dirs;
    }
Anonymous
14-Nov-2007 04:54
for ( $files = array(); ( $file = readdir( $handle )) !== false; $files[] = $file );
skysama at googles_email dot com
12-Sep-2007 07:23
Yet another view files by extension

/* NOTE:
 *  /a-d = do not include directories
 *  /b   = show files in bare mode ( no dates or filesize )
 */

<?php
$dir
= '.\\img\\';    // reminder: escape your slashes
$filetype = "*.png";
$filelist = shell_exec( "dir {$dir}{$filetype} /a-d /b" );
$file_arr = explode( "\n", $filelist );
array_pop( $file_arr ); // last line is always blank
print_r( $file_arr );
?>
minisprinter (at) naver (dot) com
21-Aug-2007 01:09
The following code is a bit nasty, it can be used to remove all files generated by apache.

You're not a root user on a system, but you sometimes need to remove all files generated by apache in a certain directory. You may use this after replacing 'bbs' at the bottom with 'directory' you want.

It tries to remove all files in a directory, but it can't unless it has an ownership. it doesn't check the ownership or permission.

<?php

function remove($dirname = '.')
{
        if (
is_dir($dirname))
        {
                echo
"$dirname is a directory.<br />";

                if (
$handle = @opendir($dirname))
                {
                        while ((
$file = readdir($handle)) !== false)
                        {
                                if (
$file != "." && $file != "..")
                                {
                                        echo
"$file<br />";

                                       
$fullpath = $dirname . '/' . $file;

                                        if (
is_dir($fullpath))
                                        {
                                               
remove($fullpath);
                                                @
rmdir($fullpath);
                                        }
                                        else
                                        {
                                                @
unlink($fullpath);
                                        }
                                }
                        }
                       
closedir($handle);
                }
        }
}

remove('bbs');

?>
nullbyte at hotmail dot com
20-Aug-2007 09:06
I haven't tested this yet, but it seems like it'll do just fine if you need files of a certain extension:

$dh = opendir($options['inputDir']);
$files = array();
while (($filename = readdir($dh)) !== false)
{
    if (substr($filename, strrpos($filename, '.')) == $options['inputExt'])
    {
        $files[] = $filename;
    }
}
closedir($dh);
moehbass at gmail dot com
12-Jul-2007 07:25
PLease disregard my last two posts. For the last one, if you're looking for files with .php extension, you also get files with any extension that ends with 'p'. I wrote the function in quite a haste and now I am too busy to fix it - so don't use it! it's no good.
moehbass at gmail dot com
12-Jul-2007 05:53
Sorry,
In my last post, if you only want to list files with certain extensions, then see how many letters this extension is, add one to it, and subtract it from the strlen of the file name. Review script below for details.
moehbass at gmail dot com
12-Jul-2007 05:27
Responding to:
johan dot mickelin at gmail dot com
31-May-2007 07:52
-------------------------------------------------------
If you want to list only a certain filetype, this case only jpg and gif files in an image directory

$dir = opendir ("../images");
        while (false !== ($file = readdir($dir))) {
                if (strpos($file, '.gif',1)||strpos($file, '.jpg',1) ) {
                    echo "$file <br />";
                }
        }
-----------------------------------------------------------------

This function would also echo files that have .gif or .jpg in their names such as myFile.gif.php (I don't know why I'd name a file like that, but I am just making a point, that's all folks!)
Perhaps a more exact way is to do the following:
...
while (false !== ($file = readdir($dir))) {
        $lenOfFileName = strlen($file);
        $extOffsetPos = $lenOfFileName - 5;
         if (strpos($file, '.gif', $extOffsetPos) ||
             strpos($file, '.jpg',$extOffsetPos) ) {
                    echo "$file <br />";
          }
...
If your extensions are more than three letters, then increase the 5 to 6 (e.g. aspx) to 7 (e.g. php51) or whatever.
johan dot mickelin at gmail dot com
01-Jun-2007 04:52
If you want to list only a certain filetype, this case only jpg and gif files in an image directory

$dir = opendir ("../images");
        while (false !== ($file = readdir($dir))) {
                if (strpos($file, '.gif',1)||strpos($file, '.jpg',1) ) {
                    echo "$file <br />";
                }
        }
schursin at gmail[deleteme] dot com
28-May-2007 03:42
code:

<?php

       
function permission($filename)
        {
           
$perms = fileperms($filename);

            if     ((
$perms & 0xC000) == 0xC000) { $info = 's'; }
            elseif ((
$perms & 0xA000) == 0xA000) { $info = 'l'; }
            elseif ((
$perms & 0x8000) == 0x8000) { $info = '-'; }
            elseif ((
$perms & 0x6000) == 0x6000) { $info = 'b'; }
            elseif ((
$perms & 0x4000) == 0x4000) { $info = 'd'; }
            elseif ((
$perms & 0x2000) == 0x2000) { $info = 'c'; }
            elseif ((
$perms & 0x1000) == 0x1000) { $info = 'p'; }
            else                                 {
$info = 'u'; }

           
// владелец
           
$info .= (($perms & 0x0100) ? 'r' : '-');
           
$info .= (($perms & 0x0080) ? 'w' : '-');
           
$info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));

           
// группа
           
$info .= (($perms & 0x0020) ? 'r' : '-');
           
$info .= (($perms & 0x0010) ? 'w' : '-');
           
$info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));

           
// все
           
$info .= (($perms & 0x0004) ? 'r' : '-');
           
$info .= (($perms & 0x0002) ? 'w' : '-');
           
$info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));

            return
$info;
        }

        function
dir_list($dir)
        {
            if (
$dir[strlen($dir)-1] != '/') $dir .= '/';

            if (!
is_dir($dir)) return array();

           
$dir_handle  = opendir($dir);
           
$dir_objects = array();
            while (
$object = readdir($dir_handle))
                if (!
in_array($object, array('.','..')))
                {
                   
$filename    = $dir . $object;
                   
$file_object = array(
                                           
'name' => $object,
                                           
'size' => filesize($filename),
                                           
'perm' => permission($filename),
                                           
'type' => filetype($filename),
                                           
'time' => date("d F Y H:i:s", filemtime($filename))
                                        );
                   
$dir_objects[] = $file_object;
                }

            return
$dir_objects;
        }

?>

call:

<?php

        print_r
(dir_list('/path/to/you/dir/'));

?>

output sample:

Array
(
    [0] => Array
        (
            [name] => api
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 01:55:02
        )

    [1] => Array
        (
            [name] => classes
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 26 May 2007 00:56:44
        )

    [2] => Array
        (
            [name] => config.inc.php
            [size] => 143
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 13:13:19
        )

    [3] => Array
        (
            [name] => index.php
            [size] => 131
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 22:15:18
        )

    [4] => Array
        (
            [name] => modules
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 00:47:40
        )

    [5] => Array
        (
            [name] => temp
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 04:49:33
        )

)
(Qube#php@Efnet)
15-May-2007 05:36
<?php

// Sample function to recursively return all files within a directory.
// http://www.pgregg.com/projects/php/code/recursive_readdir.phps

Function listdir($start_dir='.') {

 
$files = array();
  if (
is_dir($start_dir)) {
   
$fh = opendir($start_dir);
    while ((
$file = readdir($fh)) !== false) {
     
# loop through the files, skipping . and .., and recursing if necessary
     
if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
     
$filepath = $start_dir . '/' . $file;
      if (
is_dir($filepath) )
       
$files = array_merge($files, listdir($filepath));
      else
       
array_push($files, $filepath);
    }
   
closedir($fh);
  } else {
   
# false if the function was called with an invalid non-directory argument
   
$files = false;
  }

  return
$files;

}

$files = listdir('.');
print_r($files);
?>
(Qube#php@Efnet)
14-May-2007 11:41
Here is an updated version of preg_find() [which has been linked from the glob() man page for years] - this function should provide most of what you want back from reading files, directories, different sorting methods, recursion, and perhaps most powerful of all the ability to pattern match with a PCRE regex.

You can get preg_find here: http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt
or if you prefer colourful .phps format: http://www.pgregg.com/projects/php/preg_find/preg_find.phps
or scoll down to the end of this note.

I wrote several examples on how to use it on my blog at: http://www.pgregg.com/forums/viewtopic.php?tid=73

simple glob() type replacement:
$files = preg_find('/./', $dir);

recursive?
$files = preg_find('/./', $dir, PREG_FIND_RECURSIVE);

pattern match? find all .php files:
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE);

sorted alphabetically?
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE|PREG_FIND_SORTKEYS);

sorted in by filesize, in descending order?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTFILESIZE|PREG_FIND_SORTDESC);
$files=array_keys($files);

sorted by date modified?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTMODIFIED);
$files=array_keys($files);

Ok, the PHP note says my note is too long, so please click on one of the above links to get it.
phpwizard-at-pech-dot-cz
04-Jul-2002 10:22
It should work, but it'll be better to read section 13.1.3 Cache-control Mechanisms of RFC 2616 available at http://rfc.net/rfc2616.html before you start with confusing proxies on the way from you and the client.

Reading it is the best way to learn how proxies work, what should you do to modify cache-related headers of your documents and what you should never do again. :-)

And of course not reading RFCs is the best way to never learn how internet works and the best way to behave like Microsoft corp.

Have a nice day!
Jirka Pech
fridh at gmx dot net
10-Apr-2002 02:41
Someone mentioned the infinite recursion when a symbolic link was found...

tip: is_link() is a nice function :)

rewinddir> <opendir
Last updated: Fri, 26 Sep 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites