I need to list all files (which have certain extensions) in a folder and its sub-folders. I used RecursiveIteratorIterator as described in @Matthew 's great answer in PHP list all files in directory.
And one last thing: displaying a file-tree, or maybe all directories that have no sub-directories, are both examples of things that one might want to do when dealing with files. How would you recommend to pass this data to the client side and how would the data structure look like?
$filename
in that answer is actually not a string. It is an object of type SplFileInfo
which can be used like a string but it also offers much more detailed info:
SplFileInfo::getFilename()
-- filename.SplFileInfo::getPathname()
-- path to the fileSplFileInfo::getPathInfo()
-- SplFileInfo object for the pathSplFileInfo::getRealPath()
-- canonicalized absolute pathname; see realpath()
for more info and the difference to Pathname,Using this as a base:
$iter = new RecursiveDirectoryIterator('../');
foreach (new RecursiveIteratorIterator($iter) as $fileName => $fileInfo) {
$fullPath = (string) $fileInfo;
}
Each $fileInfo
will return a SplFileInfo
object. The path and filename are easily accessible in addition to a host of other methods.
phpSplFileInfo Object
(
[pathName:SplFileInfo:private] => ./t.php
[fileName:SplFileInfo:private] => t.php
)
I may be mistaken, but to access the parent folder name unless you record it through the tree the simplest would be using dirname
and appending ../
to the path.
<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ($iterator as $fileinfo) {
echo $iterator->current()->getPathname() . "\n";
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With