Listing all directories, sub directories and files starting from the root I have to deploy this code that will list all the directories, sub directories and files in it starting from the root. The code works but I am not sure if this is the correct way to list. It should not fail, though.

Also, in despite not allowing directories with the name . and .., they get printed. Why is that?

&lt;?php

# Snippet that lists all the directories,sub directories and files under that directory
# recursive function

function directory_f_lister($root) {
    $dir_list = scandir($root);
    for($var=0;$var&lt;count($dir_list);$var++) {
        if(is_readable($root.$dir_list[$var])) {
            if(is_dir($root.$dir_list[$var])) {
                if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
                echo "&lt;h3&gt;Name of directory $dir_list[$var]&lt;/h3&gt;";
                echo "&lt;br /&gt;";
                $dh = opendir($root.$dir_list[$var]);
                while(($name = readdir($dh)) !== false) {
                    if(is_dir($root.$dir_list[$var].$name)) {
                        if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
                        echo "Name of directory : &lt;strong&gt; $name &lt;/strong&gt;";
                        echo "&lt;br /&gt;";
                        directory_f_lister($root.$dir_list[$var].$name);
                    }else {
                        echo $name;
                        echo "&lt;br/&gt;";
                    }
                }
            }
        }
    }
}

directory_f_lister(DIRECTORY_SEPARATOR);
#end
well . and  .. are not directories, thats are navigationpoints of directories, . means go inside a root directory, .. means go one folder back, 

you might noticed this already in includes like include ../../../foo/bar.php 

also instead of scandir and readdir php has classes for this purpose DirectoryIterator or FileSystemIterator 

And if you wish to create reusable methods, dont do output there, instead return an array of folders/files something like

$directories = scanDirectories($rootDirectory); //create output array
foreach($directories as $directory){
    echo $directory.'&lt;br/&gt;';  
} 


this allowes you to modify the output without editing the sourcecode, you could also wrap the output within a function e.g. viewDirectories and reuse it on different places.

here is a small Example 

    ini_set('html_errors', 'On');

function scanDirectory($path) {
    $path = realpath($path);

     return  new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);

}

foreach(scanDirectory('./') as $name=&gt; $object){

    echo $name.'&lt;br/&gt;';
}


About your question:

$root.$dir_list[$var].$name //this is your directory name


but youre checking if this name is . and ..

$dir_list[$var]


so its never becomes true