Over a million developers have joined DZone.

Drop-In PHP Script For Listing Files In A Directory + Optional Passphrase Protection

·
This script can be dropped into a directory on a web server (e.g. as index.php) to provide a very basic, nice-looking directory listing of that directory.  It is made specifically to operate on the directory it is in, so it doesn't apply to subdirectories.  Additionally, you can password-protect the listing by modifying the settings near the top of the script.

The security of the password protection is probably questionable and indicative of my newness to PHP, so I wouldn't recommend using it to protect highly sensitive files.  Also, be sure any file/directory permissions are set accordingly.

Icons are borrowed from Wikimedia Commons.  Many file types aren't represented (because I'm lazy :P).






Directory Listing






Incorrect passphrase.
'; } if ( $auth == "none" || $auth == "wrong" ) { echo '
Please enter the passphrase to continue.
'; echo <<< EOT
EOT; } if ( $auth == "good" ) { // Define the path as being the current directory $path = "./"; // Open the current directory $dir_handle = @opendir($path) or die("Unable to open $path"); echo "

Directory Listing

\n"; // Loop through the directory, sticking filenames into $files[] while ($file = readdir($dir_handle)) { if ( $file[0] != '.' && stripos($file,"php") == FALSE ) $files[] = $file; } // Closing the directory closedir($dir_handle); // If the directory is empty if ( count($files) == 0 ) { echo '
Directory is empty.
'; } else { // sort the array sort($files); foreach ( $files as $file ) { $pathinfo = pathinfo($file); $ext = strtolower($pathinfo['extension']); switch ($ext) { case "jpg": $icon = "http://upload.wikimedia.org/wikipedia/commons/6/65/Image-silk.png"; break; case "png": case "gif": $icon = "http://upload.wikimedia.org/wikipedia/commons/4/4c/Page_white_paintbrush.png"; break; case "htm": case "html": $icon = "http://upload.wikimedia.org/wikipedia/commons/7/7b/Page_white_world.png"; break; case "doc": case "docx": $icon = "http://upload.wikimedia.org/wikipedia/commons/3/32/Page_word.png"; $icon = "http://upload.wikimedia.org/wikipedia/commons/a/a1/Page_white_word.png"; break; case "xls": case "xlsx": $icon = "http://upload.wikimedia.org/wikipedia/commons/9/9c/Page_excel.png"; break; case "pdf": $icon = "http://upload.wikimedia.org/wikipedia/commons/1/11/Page_white_acrobat.png"; break; case "zip": case "tar": case "jar": case "sit": case "gz": case "bz2": case "7z": $icon = "http://upload.wikimedia.org/wikipedia/commons/d/d2/Page_white_zip.png"; break; default: $icon = "http://upload.wikimedia.org/wikipedia/commons/7/75/Page_white.png"; } echo "$ext$file
\n"; } // end foreach } // end else echo ''; } ?>
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}