<?php
$basedir = "c:/Apache/www/";  // Base directory

function listall($dir)
{
    // Initialize temporary arrays for sorting
    $dir_files = $dir_subdirs = array();

    // Print current directory
    print("<ul>");
    print("<li><b>$dir</b>\n");
    
    // Change to directory
    chdir($dir);
    
    // Open directory;
    $handle = @opendir($dir) or die("Directory \"$dir\"not found.");
    
    // Loop through all directory entries, construct 
    // two temporary arrays containing files and sub directories
    while($entry = readdir($handle)) 
    {
        if(is_dir($entry) && $entry != ".." && $entry != ".")
        {
            $dir_subdirs[] = $entry;
        }
        elseif($entry != ".." && $entry != ".")
        {   
            $dir_files[] = $entry;
        }
    }

    // Sort files and sub directories
    sort($dir_files);
    sort($dir_subdirs);
    
    // Print all files in the curent directory
    for($i=0; $i<count($dir_files); $i++)
    {
        print("<li>$dir_files[$i]\n");
    }
    
    // Traverse sub directories
    for($i=0; $i<count($dir_subdirs); $i++)
    {
        listall("$dir$dir_subdirs[$i]/");
    }
    print("</ul>");
    
    // Close directory
    closedir($handle);
}

listall($basedir);
?>
Published in: PHP
Download

Related snippets