List-files-and-directories-in-a-directory

by MD on 2009/09/20

In PHP to have an automatic listing of files and folders in a directory, you can use code below. To use this effectively and regularly you should put this code in a file index.php in directory, so whenever someone will access that directory through browser, all the files and folders will be listed with links.

<?php
    // This script list name of all the subdirectories and files in a directory
    if ($handle = opendir('.')) {
        while (false !== ($file = readdir($handle))) {
            if ($file != "." && $file != "..") {
                $thelist .= ' '.$file.'';
            }
        }
        closedir($handle);
    }
?>

 This is the list of files in this directory: 

Or you can write in the code in this manner also.

<?php
    // Define the full path to your folder from root
    $path = ".";
    // Open the folder
    $dir_handle = @opendir($path) or die("Unable to open $path");
   // Loop through the files
    while ($file = readdir($dir_handle)) {
        if ($file == "." || $file == ".." || $file == "index.php" )
        continue;
        echo "$file";
    }	// Close
    closedir($dir_handle);
?>

But if you wish to list both files and directories separately, following code can be used, this separately print directories and files.

<?php
// get array of all files and directories in the current directory (it is sorted alphabetically by default)
$dir_entries = scandir(dirname(__FILE__)); // for PHP 5.3+, use __DIR__ instead of dirname(__FILE__)

// split the array of files and directories into two arrays, one containing files and the other directories
$dir_files = array();
$dir_directories = array();
foreach($dir_entries as $dir_entry) {
    if(is_dir($dir_entry)) {
        array_push($dir_directories, $dir_entry);
    } else {
        array_push($dir_files, $dir_entry);
    }
}

// print directories
foreach($dir_directories as $dir_directory) {
    // don't print current and parent directories
    if($dir_directory == '.' or $dir_directory == '..') {
        continue;
    }
    echo "" . htmlspecialchars($dir_directory) . "\n";
}

// print files
foreach($dir_files as $dir_file) {
    echo "" . htmlspecialchars($dir_file) . "\n";
}
?>

You may also like:

Leave a Comment

Previous post:

Next post: