Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the RecursiveDirectoryIterator [duplicate]

Tags:

php

Possible Duplicate:
Displaying folders and making links of those folders

I'm trying to create a simple file browser using the RecursiveDirectoryIterator but can't seem to figure it out... Any help please?

$cwd = '/path/to/somewhere';
if(isset($_GET['path']) && is_dir($cwd.$_GET['path'])) {
    $cwd .= $_GET['path'];
}

$dir = new RecursiveDirectoryIterator($cwd);
$iter = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
while($iter->valid()) {
    // skip unwanted directories
    if(!$iter->isDot()) {
        if($iter->isDir()) {
            // output linked directory along with the number of files contained within
            // for example: some_folder (13)
        } else {
            // output direct link to file
        }
    }
    $iter->next();
}

Not sure if this is the best approach, but I'm under the impression that the RecursiveDirectoryIterator is faster than both the opendir() and glob() methods.

like image 303
mister martin Avatar asked Dec 26 '22 17:12

mister martin


1 Answers

SELF_FIRST and CHILD_FIRST as nothing to do with RecursiveDirectoryIterator but RecursiveIteratorIterator

If you run

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::SELF_FIRST );

foreach ( $iterator as $path ) {
    if ($path->isDir()) {
        print($path->__toString() . PHP_EOL);
    } else {
        print($path->__toString() . PHP_EOL);
    }

You would get

...\htdocs\lab\stockoverflow\css
...\htdocs\lab\stockoverflow\css\a.css
...\htdocs\lab\stockoverflow\css\b.css
...\htdocs\lab\stockoverflow\css\c.css
...\htdocs\lab\stockoverflow\css\css.php
...\htdocs\lab\stockoverflow\css\css.run.php

If you change it to RecursiveIteratorIterator::CHILD_FIRST

...\htdocs\lab\stockoverflow\css\a.css
...\htdocs\lab\stockoverflow\css\b.css
...\htdocs\lab\stockoverflow\css\c.css
...\htdocs\lab\stockoverflow\css\css.php
...\htdocs\lab\stockoverflow\css\css.run.php
...\htdocs\lab\stockoverflow\css

Can you see the difference is in the position of the current folder

like image 69
Baba Avatar answered Jan 08 '23 21:01

Baba