文字

The DirectoryIterator class

(PHP 5)

简介

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

类摘要

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 extends SplFileInfo.

Table of Contents

  • DirectoryIterator::__construct — Constructs a new directory iterator from a path
  • DirectoryIterator::current — Return the current DirectoryIterator item.
  • DirectoryIterator::getATime — Get last access time of the current DirectoryIterator item
  • DirectoryIterator::getBasename — Get base name of current DirectoryIterator item.
  • DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item
  • DirectoryIterator::getExtension — Gets the file extension
  • DirectoryIterator::getFilename — Return file name of current DirectoryIterator item.
  • DirectoryIterator::getGroup — Get group for the current DirectoryIterator item
  • DirectoryIterator::getInode — Get inode for the current DirectoryIterator item
  • DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item
  • DirectoryIterator::getOwner — Get owner of current DirectoryIterator item
  • DirectoryIterator::getPath — Get path of current Iterator item without filename
  • DirectoryIterator::getPathname — Return path and file name of current DirectoryIterator item
  • DirectoryIterator::getPerms — Get the permissions of current DirectoryIterator item
  • DirectoryIterator::getSize — Get size of current DirectoryIterator item
  • DirectoryIterator::getType — Determine the type of the current DirectoryIterator item
  • DirectoryIterator::isDir — Determine if current DirectoryIterator item is a directory
  • DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::isExecutable — Determine if current DirectoryIterator item is executable
  • DirectoryIterator::isFile — Determine if current DirectoryIterator item is a regular file
  • DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link
  • DirectoryIterator::isReadable — Determine if current DirectoryIterator item can be read
  • DirectoryIterator::isWritable — Determine if current DirectoryIterator item can be written to
  • DirectoryIterator::key — Return the key for the current DirectoryIterator item
  • DirectoryIterator::next — Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start
  • DirectoryIterator::seek — Seek to a DirectoryIterator item
  • DirectoryIterator::__toString — Get file name as a string
  • DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

用户评论:

[#1] abdel at elghafoud dot com [2014-02-20 11:39:41]

Shows us recursively all files and catalogues in directory except "." and "..".

<?php


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;
}

?>

[#2] rogier at dsone dot nl [2012-08-16 18:23:44]

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

[#3] Kunal Bhatia->kmasterzone@gmail dot com [2011-04-15 02:48:15]

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++;
        }
    }
?>

[#4] krystianmularczyk at gmail dot com [2009-01-25 03:31:31]

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";
}

?>

[#5] David Lanstein [2009-01-21 12:50:27]

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;
        }
    }
}
?>

[#6] Mark van Straten [2008-07-09 07:56:51]

Implements Iterator so you can foreach() over the content of the given directory

上一篇: 下一篇: