script to list directories won't work

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
chiyosdad
Forum Newbie
Posts: 4
Joined: Wed Dec 24, 2003 11:46 am

script to list directories won't work

Post 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?
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post 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.
Post Reply