8

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.

  • I'm setting the root of the search to ".." and all filenames get a prefix of "../". How can I get the filename only?
  • How can I get, in addition to the filename, its parent folder name?
  • ...and how can I get the full path of the filename?

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?

Community
  • 1
  • 1
user1639431
  • 3,693
  • 8
  • 24
  • 22

3 Answers3

11

$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:

hakre
  • 193,403
  • 52
  • 435
  • 836
sectus
  • 15,605
  • 5
  • 55
  • 97
3

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
Martin
  • 6,632
  • 4
  • 25
  • 28
  • Martin, what kind of exception are you trying to catch? Documentation said nothing about exceptions in `__toString()`. – sectus Mar 18 '13 at 03:18
  • Oops, I pasted it from an open file I had which utilises functions which do throw exceptions, forgot to remove it.. Fixed! – Martin Mar 18 '13 at 03:50
  • @Martin: Cast to string instead of using `->__toString()`. This is what is intended by that function *and* it does not leak any exceptions. (You may have done that for debug reasons, but for code here, take the straight variant). – hakre Apr 26 '13 at 19:17
  • Also I think you wanted to outline that that the object also offers a path relative to the base-path of the recursive directory iterator. You might want to make this more visible / show a little demonstration. Just commenting. – hakre Apr 26 '13 at 19:18
1
<?php
    $iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::CURRENT_AS_PATHNAME);
    foreach ($iterator as $fileinfo) {
        echo $iterator->current()->getPathname() . "\n";
    }
 ?>
Milind Morey
  • 2,100
  • 19
  • 15