Recursive directory iterator php

The RecursiveDirectoryIterator class

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

Class synopsis

public__construct(string $directory , int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO)

public getChildren(): RecursiveDirectoryIterator
public getSubPathname(): string
public hasChildren(bool $allowLinks = false): bool
public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator
public FilesystemIterator::getFlags(): int
public FilesystemIterator::key(): string
public FilesystemIterator::next(): void
public FilesystemIterator::rewind(): void
public FilesystemIterator::setFlags(int $flags): void
public DirectoryIterator::current(): mixed
public DirectoryIterator::getATime(): int
public DirectoryIterator::getBasename(string $suffix = ""): string
public DirectoryIterator::getCTime(): int
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::getGroup(): int
public DirectoryIterator::getInode(): int
public DirectoryIterator::getMTime(): int
public DirectoryIterator::getOwner(): int
public DirectoryIterator::getPath(): string
public DirectoryIterator::getPathname(): string
public DirectoryIterator::getPerms(): int
public DirectoryIterator::getSize(): int
public DirectoryIterator::getType(): string
public DirectoryIterator::isDir(): bool
public DirectoryIterator::isDot(): bool
public DirectoryIterator::isExecutable(): bool
public DirectoryIterator::isFile(): bool
public DirectoryIterator::isLink(): bool
public DirectoryIterator::isReadable(): bool
public DirectoryIterator::isWritable(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int $offset): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string

Table of Contents

  • RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory
  • RecursiveDirectoryIterator::getSubPath — Get sub path
  • RecursiveDirectoryIterator::getSubPathname — Get sub path and name
  • RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not ‘.’ or ‘..’
  • RecursiveDirectoryIterator::key — Return path and filename of current dir entry
  • RecursiveDirectoryIterator::next — Move to next entry
  • RecursiveDirectoryIterator::rewind — Rewind dir back to the start
Читайте также:  Python for list pop
PHP 8.2

(PHP 5 5.4.0, 7, 8) The callback should accept up to three arguments: current item, key and iterator, respectively.

(PHP 5 5.1.0, 7, 8) Classes implementing RecursiveIterator can be used iterate over iterators recursively.

Источник

Recursive Directory Iterator

How to use DirectoryIterator and RecursiveDirectoryIterator classes to loop through all files and folders inside a directory.

Using a DirectoryIterator to Find Files in a Folder

Iterate is a term for looping, a DirectoryIterator class can loop through files in folders (directories) and RecursiveDirectoryIterator class can loop through files in directories recursively. Here’s an example:

Example: DirectoryIterator using while loop

Use the while loop with DirectoryIterator::valid() and DirectoryIterator::next() , the while loop repeats a code block as many times as there are items in a directory:

The valid() method of the DirectoryIterator object returns true if it currently points to a valid item in the directory. The next() method cause the DirectoryIterator object to point to the next item in the directory.

Example: DirectoryIterator using foreach loop

The isDot() method identifies the special files . (current directory) and .. (parent directory).

Example: Using isDir(), isFile(), and isLink() etc.

isDir()) echo 'Directory: '. $file.'
'; else if ($file->isFile()) echo 'File: '. $file.'
'; else if ($file->isLink()) echo 'Symlink: '. $file.'
'; else echo 'Other: '. $file.'
'; >
  • The isDir() method determines if the current item is a directory.
  • The isFile() method determines if the current item is a regular file.
  • The isLink() method determines if the current item is a symbolic link.

Iterating recursively over directories with RecursiveDirectoryIterator

The DirectoryIterator class iterate over a single directory, use the RecursiveDirectoryIterator class if you need to find files down into subdirectories. This class automatically enters any subdirectory and iterates through its contents. To iterate over a directory recursively, you need to wrap RecursiveDirectoryIterator object in the RecursiveIteratorIterator object.

'; > /*Prints: D:\xampp\htdocs\. D:\xampp\htdocs\.. D:\xampp\htdocs\.htaccess D:\xampp\htdocs\3d\. D:\xampp\htdocs\3d\.. . */

To access only the filenames use getFilename() methods:

getFilename() . '
'; > /* Prints: . .. .htaccess . .. cycles-renderer-reflection-yt.html . .. 12047a40.png */

Example: using flags to skip current . and parent directory ..

getFilename() . '
'; > /* Prints: .htaccess cycles-renderer-reflection-yt.html 12047a40.png */

Working with Files in PHP:

Источник

The DirectoryIterator class

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

Class synopsis

public SplFileInfo::openFile ( string $mode = «r» , bool $useIncludePath = false , ? resource $context = null ): SplFileObject

Table of Contents

  • DirectoryIterator::__construct — Constructs a new directory iterator from a path
  • DirectoryIterator::current — Return the current DirectoryIterator item
  • DirectoryIterator::getBasename — Get base name of current DirectoryIterator item
  • DirectoryIterator::getExtension — Gets the file extension
  • DirectoryIterator::getFilename — Return file name of current DirectoryIterator item
  • DirectoryIterator::isDot — Determine if current DirectoryIterator item is ‘.’ or ‘..’
  • 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

User Contributed Notes 8 notes

Shows us all files and catalogues in directory except «.» and «..».

foreach (new DirectoryIterator ( ‘../moodle’ ) as $fileInfo ) if( $fileInfo -> isDot ()) continue;
echo $fileInfo -> getFilename () . «
\n» ;
>

DirectoryIterator is just an lightweight SplFileInfo iterator and its methods operate on whatever item the internal cursor points to. In other words:

$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».

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:

// 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 );

?>

expected result: /projects/lang (or C:/projects/lang)
actual result: C:\projects\lang

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.

// 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():

class AllTestsFilterIterator extends FilterIterator <
public function accept () <
if ( preg_match ( ‘/All.*Tests\.php/’ , $this -> current ())) <
return true ;
> else <
return false ;
>
>
>
?>

Источник

Оцените статью