Better directory listing with PHP
March 3rd, 2008
When a web browser is pointed to a directory on your website which does not have an index.htm(l) in it, the files in that directory can be listed on a web page.
It’s typical for most server setup that directory listing is disabled. You can overwrite apache’s options with .htaccess file.
Just Change:
Options +Indexes
If you do use this option, be very careful that you do not put any unintentional or compromising files in this directory. And if you guessed it by the plus sign before Indexes, you can throw in a minus sign (Options -Indexes) to prevent directory listing entirely.
If you want the directory contents to be listed, but only if they were HTML pages and not images:
IndexIgnore *.gif *.jpg
I used this for years without problems but now I wanted to have a better look for the list.
My idea was a PHP script that takes the file structure of a specified folder and outputs it into a stylable format. It should simply lists the different folders as links, but not in the standard (boring) format. I want to be able to put it in my template.
Solution is a PHP script that has a definied path (or takes the path where the script is located) and then uses opendir function to generate an array. When iterating the array a difference has to be made if the accessed item is a file or directory.
Additionally the filesize of each item is detected.
<?php $dir = opendir (dirname(__FILE__)); $exclude = array("index.php", ".", ".."); while($fn = readdir($dn)) { if ($fn == $exclude[0] || $fn == $exclude[1] || $fn == $exclude[2]) continue; $list[] = $fn; } sort($list); foreach ($list as $item) { if (is_dir($item)){ $dir .= "<img src='/img/dir.png'> <a href='$item'>$item</a><br>"; }else{ $size= filesize($item); $m = 'bytes'; if ($size > 1024) { $size=round($size/1024,2); $m = 'KB'; } elseif ($size > 1024*1024){ $size = round(($size/1024)/1024,2); $m = 'MB'; } $a .= "<img src='/img/file.png'> <a href='$item'>$item</a> - $size ($m)<br>"; } echo $dir . $a; } closedir($dir); ?>
This works well but it it has no great advantage over the standard directory listing. The script can be put into a nice styled page that is not as boring as the standard. It would have costed me some time to extract the filetype out of the filename and then load an appropriate image for it.
To save time my choice is a script that generates a well formed table, listing the contents of a specified directory and sub-directories. Has image tags associated with certain file types and the ability to generate thumbnails to preview image files.
Directory Listing Script by Evoluted

A different styled solutions is PHP Directory Listing on freshmeat.net. It displays the content of a directory and automatically creates thumbnails. Caching is done for JPEG, GIF, and PNG files.
A stylish directory listing continuously improves the user-friend user friendliness a lot.





