dir

(PHP 3, PHP 4, PHP 5)

dir -- Класс directory

Описание

class dir {

dir ( string каталог )

string path

resource handle

string read ( void )

void rewind ( void )

void close ( void )

}

Псевдо-объектно-ориентированный механизм для чтения каталога, переданного в параметре каталог. С момента открытия каталога становятся доступными два свойства класса. Свойство "handle" может быть использовано с другими функциями для работы с каталогами, например, с функциями readdir(), rewinddir() и closedir(). Свойство "path" содержит путь к открытому каталогу. Доступны три метода: read, rewind and close.

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

Пример 1. Пример использования класса dir()

<?php
$d
= dir("/etc");
echo
"Дескриптор: ".$d->handle."<br>\n";
echo
"Путь: ".$d->path."<br>\n";
while (
false !== ($entry = $d->read())) {
   echo
$entry."<br>\n";
}
$d->close();
?>

Замечание: Порядок, в котором метод "read" возвращает элементы каталога, зависит от операционной системы.

Замечание: Также, PHP автоматически определяет внутренний класс Directory, что означает, что вы не сможете определять собственные классы с таким же именем. За полным списком предопределенных классов обратитесь к главе Предопределенные классы.



dir
22-Feb-2006 01:02
Regarding samuel's comment about the dir() function not supporting Unicode properly, it's all in the encoding. The function does NOT internally change Unicode characters into question marks (?), as I was first led to believe. If you simply try to output them in UTF-8, they'll show up just right.
samuel dot l at mushicrew dot com
24-Jan-2006 10:52
Note that the dir object will use the default encoding for non-unicode programs on Windows with PHP 5.x.

So, if you have a file named with characters unsupported by the current default encoding, the dir->read() method will return a wrong entry.

<?php
/*
** This script is on the same directory than a file named with
** unsupported characters for the current default encoding.
*/
$d = dir("./");
while(
false !== ($e = $d->read()))
   echo
$e . '<br/>';
?>

This will print a "?" for every unsupported characters, and not the right file name. So take care if you check with is_file/is_dir right after enumerating.
radar at frozenplague dot net
13-Jan-2006 12:00
Regarding jaqb's post about a correction to the read_dir function, I have one small fix too if people wish to also list the directories inside this directory and read them into the same array.

<?
function read_dir($dir) {
  
$array = array();
  
$d = dir($dir);
   while (
false !== ($entry = $d->read())) {
       if(
$entry!='.' && $entry!='..') {
          
$entry = $dir.'/'.$entry;
           if(
is_dir($entry)) {
              
$array[] = $entry;
              
$array = array_merge($array, read_dir($entry));
           } else {
              
$array[] = $entry;
           }
       }
   }
  
$d->close();
   return
$array;
}
?>
fordiman at gmail dot com
10-Jan-2006 10:15
Saw the leaf dirs bit...  quick mod:

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
   $pat=preg_replace ("|(/.*/[^S]*)|s", "\\1S", $pat);
   while (substr ($path,-1,1) =="/") $path=substr ($path,0,-1);
   if (!is_dir ($path) ) $path=dirname ($path);
   if ($rec!==true) $rec=false;
   $d=dir ($path);
   $ret=Array ();
   while (false!== ($e=$d->read () ) ) {
       if ( ($e==".") || ($e=="..") ) continue;
       if ($rec && is_dir ($path."/".$e) ) {
           $ret=array_merge ($ret,preg_ls($path."/".$e,$rec,$pat));
           continue;
       }
       if (!preg_match ($pat,$e) ) continue;
       $ret[]=$path."/".$e;
   }
   return (empty ($ret) && preg_match ($pat,basename($path))) ? Array ($path."/") : $ret;
}

example:

foreach (preg_ls ("/usr/share/fluxbox", true, "/[LT]e[sa]/i") as $file) echo $file."\n";

output:

/usr/share/fluxbox/styles/Leaf/
/usr/share/fluxbox/styles/Clean
/usr/share/fluxbox/styles/Testing/
fordiman at gmail dot com
10-Jan-2006 10:05
This one's pretty nice.  After getting frustrated for hunting down .jpg files in my massive music collection (PHP would run out of memory), I thought there should be a preg_ls function.

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
   // it's going to be used repeatedly, ensure we compile it for speed.
   $pat=preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat);
   //Remove trailing slashes from path
   while (substr($path,-1,1)=="/") $path=substr($path,0,-1);
   //also, make sure that $path is a directory and repair any screwups
   if (!is_dir($path)) $path=dirname($path);
   //assert either truth or falsehoold of $rec, allow no scalars to mean truth
   if ($rec!==true) $rec=false;
   //get a directory handle
   $d=dir($path);
   //initialise the output array
   $ret=Array();
   //loop, reading until there's no more to read
   while (false!==($e=$d->read())) {
       //Ignore parent- and self-links
       if (($e==".")||($e=="..")) continue;
       //If we're working recursively and it's a directory, grab and merge
       if ($rec && is_dir($path."/".$e)) {
           $ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat));
           continue;
       }
       //If it don't match, exclude it
       if (!preg_match($pat,$e)) continue;
       //In all other cases, add it to the output array
       $ret[]=$path."/".$e;
   }
   //finally, return the array
   return $ret;
}

Not bad for a mere 18 lines, don't you think?

Example use:

foreach (preg_ls("/etc/X11", true, "/.*\.conf/i") as $file) echo $file."\n";

Output:

/etc/X11/xkb/README.config
/etc/X11/xorg.conf-vesa
/etc/X11/xorg.conf~
/etc/X11/gui.conf
/etc/X11/xorg.conf
/etc/X11/xorg.conf-fbdev
Anton Backer
04-Jan-2006 07:24
i've modified the script below to get the leaf folders of any directory (folders with no subfolders).

note: this does not return the folder passed in as a parameter, even if it has no subfolders.

<?php
function get_leaf_dirs($dir) {
  
$array = array();
  
$d = dir($dir);
   while (
false !== ($entry = $d->read())) {
       if(
$entry!='.' && $entry!='..') {
          
$entry = $dir.'/'.$entry;
           if(
is_dir($entry)) {
              
$subdirs = get_leaf_dirs($entry);
               if (
$subdirs)
                
$array = array_merge($array, $subdirs);
               else
                
$array[] = $entry;
           }
       }
   }
  
$d->close();
   return
$array;
}
?>

<chrootclosedir>
 Last updated: Tue, 15 Nov 2005