kr16kr asked:
How to write a PHP coding to list out all files and directories as links to them?
How to write a PHP coding to list out all files and directories as links to them?
This is somewhat similar to some index pages. When new file or folder is added to the directory, HTML page should display the newly created file/folder together with previous ones after it is being refreshed. (prefer in alphabatical order)
How to achieve this sort of functionality in PHP? Please provide sample coding as well. (and any references)
Thanks.
Tags: Php Sample


// 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”;
}