Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make RecursiveDirectoryIterator skip unreadable directories?

foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".")) as $file) {
  echo "$file\n";
}

Is there any way for this code to not throw UnexpectedValueException "failed to open dir: Permission denied" whenever there is a unreadable subdirectory inside directory I attempt to list?

UPDATE

Converting foreach() to while() and explicitly calling Iterator::next() wrapped in try() catch {} doesn't help. This code:

$iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("."));
while($iter->valid()) {
    $file = $iter->current();
    echo "$file\n";
    try {
        $iter->next();
    } catch(UnexpectedValueException $e) {
    }
};

is an infinite loop if there is unreadable subdirectory.

like image 787
Kamil Szot Avatar asked Dec 28 '10 16:12

Kamil Szot


1 Answers

Apparently you can pass $flags parameter to constructor. There's only one flag in the docs, but it does exactly what you want: catches exceptions during getChildren() calls and simply jumps to the next element.

Change your class creation code to

new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator("."), 
    RecursiveIteratorIterator::LEAVES_ONLY,
    RecursiveIteratorIterator::CATCH_GET_CHILD);

and it should work

like image 72
German Rumm Avatar answered Oct 05 '22 22:10

German Rumm