The explanation of Rubens Ribeiro, author of blog PHP is very good:
DirectoryIterator
The DirectoryIterator
class implements the Iterator
interface, it
has the methods to manipulate the "pointer" for the item traversed.
For example, you have the rewind
method to go back to the first
position. Also, since you implement the SeekableIterator
interface,
has the seek
method, which moves the pointer to a desired position.
FilesystemIterator
The class FilesystemIterator
that extends the class
DirectoryIterator
, and offers additional features. For example,
inform binary flags to get some behaviors, such as:
- Ignore the "." and ".."
- Follow symbolic links
- Specify the return type of the
current
method (used in iterations with foreach
), etc.
GlobIterator
Although it's not in your question, I find it interesting to mention that there is also the GlobIterator
class.
Class GlobIterator
extends class FilesystemIterator
e
offers the additional feature of scrolling through items from a
expression, as shown with the glob function. However, for some
reason, the iterator does not have a similar behavior
to that proposed by the GLOB_BRACE
option.
Usage recommendation
The use of these classes is recommended because they offer the same features as opendir
, readdir
and closedir
(and some new ones), and is aligned with the Object Oriented model, PHP
has been hiking. The only disadvantage is incompatibility with older versions of PHP
(lower than version 5).
Difference
DirectoryIterator
is an extension of SplFileInfo
and FilesystemIterator
is an extension of DirectoryIterator
. And both implement Iterator
, Traversable
, SeekableIterator
.
Example DirectoryIterator
:
$it = new DirectoryIterator(__DIR__);
foreach ($it as $fileinfo) {
if (!$fileinfo->isDot())
var_dump($fileinfo->getFilename());
}
Example FilesystemIterator
:
$it = new FilesystemIterator(__DIR__);
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
I've removed the examples from this stackoverflow answer .
Read the complete article at: Browse Directories and Files with PHP .