PHP: Displaying Full Directory Listing

Friday, March 6, 2009

Most web servers display a list of all files in a directory, allowing users to select any one of their choosing. However, this is usually turned off for security reasons. You don't want users stumbling around your web server and finding access to files that they shouldn't.

Nevertheless, there are times when you want to give users access to a particular directory. Via custom PHP, you can easily choose which files to display and which to remain hidden. Also you can format the data in whatever style you want, making it have a completely custom look that matches your website. The following script explains how.

Custom index.php File

<?php
$files = array();
$d = dir('.');

while (false !== ($file = $d->read())) {
    if ( ($file{0} != '.') &&
         ($file{0} != '~') &&
         (substr($file, -3) != 'LCK') &&
         ($file != basename($_SERVER['PHP_SELF']))    ) {
        $files[$file] = stat($file);
    }
}

$d->close();

echo '<style>td { padding-right: 10px; }</style>';
echo '<table><caption>The contents of this directory:</caption>';

ksort($files);

date_default_timezone_set('America/New_York');

foreach ($files as $name => $stats) {
    echo "<tr><td><a href=\"{$name}\">{$name}</a></td>\n";
    echo "<td align='right'>{$stats['size']}</td>\n";
    echo '<td>', date('m-d-Y h:ia', $stats['mtime']), "</td></tr>\n";
}
echo '</table>';
?>


The script uses a call to stat() to retrieve vital statistics about the file. This function returns many attributes of the file, including its current access restrictions, owner, size, various timestamps, and more. It is a powerful function, and it is recommended that you read the full documentation at http://php.net/stat.

Hope it helps.

0 comments: