Класс DirectoryIterator

(PHP 5, PHP 7)

Введение

Класс DirectoryIterator предоставляет простой интерфейс для просмотра содержимого каталогов файловой системы.

Обзор классов

DirectoryIterator extends SplFileInfo implements SeekableIterator {
/* Методы */
public __construct ( string $path )
public DirectoryIterator current ( void )
public int getATime ( void )
public string getBasename ([ string $suffix ] )
public int getCTime ( void )
public string getExtension ( void )
public string getFilename ( void )
public int getGroup ( void )
public int getInode ( void )
public int getMTime ( void )
public int getOwner ( void )
public string getPath ( void )
public string getPathname ( void )
public int getPerms ( void )
public int getSize ( void )
public string getType ( void )
public bool isDir ( void )
public bool isDot ( void )
public bool isExecutable ( void )
public bool isFile ( void )
public bool isLink ( void )
public bool isReadable ( void )
public bool isWritable ( void )
public string key ( void )
public void next ( void )
public void rewind ( void )
public void seek ( int $position )
public string __toString ( void )
public bool valid ( void )
}

Список изменений

Версия Описание
5.1.2 DirectoryIterator наследует класс SplFileInfo.

Содержание

Коментарии

Автор:
Implements Iterator so you can foreach() over the content of the given directory
2008-07-09 10:56:51
http://php5.kiev.ua/manual/ru/class.directoryiterator.html
Автор:
DirectoryIterator::getBasename() has been also been available since 5.2.2, according to the changelog (not documented yet).  It takes a parameter $suffix, and is useful if, for instance, you use a naming convention for your files (e.g. ClassName.php). 

The following code uses this to add recursively All*Tests.php in any subdirectory off of tests/, basically, suites of suites.

<?php
// PHPUnit boilerplate code goes here

class AllTests {
    public static function 
main() {
       
$parameters = array('verbose' => true);
       
PHPUnit_TextUI_TestRunner::run(self::suite(), $parameters);
    }

    public static function 
suite() {
       
$suite = new PHPUnit_Framework_TestSuite('AllMyTests'); // this must be something different than the class name, per PHPUnit
       
$it = new AllTestsFilterIterator(
                  new 
RecursiveIteratorIterator(
                      new 
RecursiveDirectoryIterator(dirname(__FILE__) . '/tests')));

        for (
$it->rewind(); $it->valid(); $it->next()) {
            require_once(
$it->current());
           
$className $it->current()->getBasename('.php');
           
$suite->addTest($className::suite());
        }

        return 
$suite;
    }
}
?>

Also, the AllTestsFilterIterator above extends FilterIterator, and contains one method, accept():

<?php
class AllTestsFilterIterator extends FilterIterator {
    public function 
accept() {
        if (
preg_match('/All.*Tests\.php/'$this->current())) {
            return 
true;
        } else {
            return 
false;
        }
    }
}
?>
2009-01-21 14:50:27
http://php5.kiev.ua/manual/ru/class.directoryiterator.html
Shows us all files and catalogues in directory except "." and "..".

<?php

foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if(
$fileInfo->isDot()) continue;
    echo 
$fileInfo->getFilename() . "<br>\n";
}

?>
2009-01-25 05:31:31
http://php5.kiev.ua/manual/ru/class.directoryiterator.html
Deleting all files in a directory except the one which is last modified.
<?php
    $directory 
dirname(__FILE__)."/demo";
   
$filenames = array();
   
$iterator = new DirectoryIterator($directory);
    foreach (
$iterator as $fileinfo) {
        if (
$fileinfo->isFile()) {
           
$filenames[$fileinfo->getMTime()] = $fileinfo->getFilename();
        }
    }
   
ksort($filenames);
   
print_r($filenames);
    echo 
"\n";
   
$i=0;
    if(
sizeof($filenames)>1){
        foreach (
$filenames as $file){
            if(
$i>0){
                echo 
$file."\n";
               
unlink($directory."/".$file);
            }
           
$i++;
        }
    }
?>
2011-04-15 05:48:15
http://php5.kiev.ua/manual/ru/class.directoryiterator.html
Beware of the behavior when using FilesystemIterator::UNIX_PATHS, it's not applied as you might expect.

I guess this flag is added especially for use on windows.
However, the path you construct the RecursiveDirectoryIterator or FilesystemIterator with will not be available as a unix path.
I can't say this is a bug, since most methods are just purely inherited from DirectoryIterator.

In my test, I'd expected a complete unix path. Unfortunately... not quite as expected:

<?php
         
// say $folder = C:\projects\lang

       
$flags FilesystemIterator::KEY_AS_PATHNAME FilesystemIterator::CURRENT_AS_FILEINFO FilesystemIterator::SKIP_DOTS FilesystemIterator::UNIX_PATHS;
       
$d_iterator = new RecursiveDirectoryIterator($folder$flags);

        echo 
$d_iterator->getPath();

?>

expected result: /projects/lang (or C:/projects/lang)
actual result: C:\projects\lang
2012-08-16 21:23:44
http://php5.kiev.ua/manual/ru/class.directoryiterator.html
Shows us recursively all files and catalogues in directory except "." and "..".

<?php

/**
 * @param string $directory
 * @param array $files
 * @return array
 */
public function recursiveDirectoryIterator ($directory null$files = array()) {
   
$iterator = new \DirectoryIterator $directory );

    foreach ( 
$iterator as $info ) {
        if (
$info->isFile ()) {
           
$files [$info->__toString ()] = $info;
        } elseif (!
$info->isDot ()) {
           
$list = array($info->__toString () => $this->recursiveDirectoryIterator(
                       
$directory.DIRECTORY_SEPARATOR.$info->__toString ()
            ));
            if(!empty(
$files))
               
$files array_merge_recursive($files$filest);
            else {
               
$files $list;
            }
        }
    }
    return 
$files;
}

?>
2014-02-20 13:39:41
http://php5.kiev.ua/manual/ru/class.directoryiterator.html
DirectoryIterator is just an lightweight SplFileInfo iterator and its methods operate on whatever item the internal cursor points to. In other words:

<?php
$iterator 
= new DirectoryIterator('C:\\');
echo 
$iterator->getPathname();
?>

... will NOT print "C:\" but the path of the first file or subdirectory retrieved, e.g. "C:\$Recycle.Bin".
2017-10-19 18:27:55
http://php5.kiev.ua/manual/ru/class.directoryiterator.html
Автор:
For some reason, the `isDot()` method doesn't return positive for the `.DS_Store` file generated by Mac OS's Finder. In practice, I've had to write code to explicitly check for this file:

<?php

foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if(
$fileInfo->isDot() || $fileInfo->getBasename() === '.DS_Store') continue;
    echo 
$fileInfo->getFilename() . "<br>\n";
}

?>
2018-03-06 02:03:09
http://php5.kiev.ua/manual/ru/class.directoryiterator.html

    Поддержать сайт на родительском проекте КГБ