Page 1 of 1

script to list directories won't work

Posted: Thu Dec 25, 2003 10:52 pm
by chiyosdad
Hey, yeah, I'm writing a script to list the files and subdirectories of a directory (it's like a tree command). The code is

Code: Select all

<?php 
function listDir($r00t, $tab)
&#123;
	
	if(is_dir($r00t))
	&#123;
		$n = 0;
		if(!($dh = opendir($r00t))) echo "Failed to open directory $r00t <br>";
		else while(false !== ($fille = readdir($dh)))
		&#123;
			echo $tab.$n.' '.$fille.'<br>';
			$n++;
			if(substr($fille, 0, 1) != '.') listDir($r00t.'/'.$fille, $tab.$tab);	
		&#125;
			closdir($dh);
	&#125;
&#125;

listDir(getcwd().'/pi','&nbsp&nbsp&nbsp&nbsp');
?>
The output was

Code: Select all

0 .
    1 ..
    2 table3.htm
    3 172
        0 .
        1 ..
        2 23
                0 .
                1 ..
                2 testbinarysearch.php
Now, in reality, i know that the tree looks like this

Code: Select all

pi (dir)
 - files
 - 172 (dir)
     - files
     - 23 (dir)
     - 24 (dir)
 - 173 (dir)
     - more stuff
So obviously, there's some kind of problem when the function comes out of the recursion that doesn't get the rest of the subdirectories. Help, anyone?

Posted: Thu Jan 01, 2004 5:22 am
by JAM

Code: Select all

function listDir($r00t, $tab) {
    if (is_dir($r00t)) {
        $n = 0;
        if (!$dh = opendir($r00t)) {
            echo "Failed to open directory $r00t <br>";
        } else {
            while ($fille = readdir($dh)) {
                echo $tab.' '.$n.' '.$fille.'<br>';
                $n++;
                if (substr($fille, 0, 1) != '.') {
                    listDir($r00t.'/'.$fille, $tab.$tab);
                }
            }
        closedir($dh);
        }
    }
}
...worked for me.