The other day, I heard a few people talking about needing an easy way to browse images on a remote Apache server that has Indexes disabled.

They had a ~20 line php script that they were dropping into each directory in order to generate indices. The problem came when they started organizing the images into subdirectories. Eventually, it became necessary to copy the new script into a mind-bogglingly large number of directories. Inevitably, dirs were missed, etc...

I interjected that I could probably fix their problem in 30 minutes.

So I did.

<?
$base = getcwd();
$subdir = trim($_GET['dir']);

$dir = realpath("$base/$subdir");
$valid = strpos($dir, $base);
if( !$dir || $valid === FALSE || $valid != 0 )
    die();

$imgdir = dirname($_SERVER['SCRIPT_NAME']);

echo "<h3>$subdir</h3>\\\n";
$dirs = "";
$imgs = "<hr/>\\\n";

if( file_exists($dir) && is_dir($dir) ) {
    $dh = opendir($dir);
    while( false !== ($file = readdir($dh)) ) {
        if( $file == "." || $file == ".." || $file == ".svn" || substr($file,-4) == ".php" )
            continue;
        if( is_dir("$base/$subdir/$file") ) {
            $dirs .= "<span>|<a href='?dir=$subdir/$file'>$file</a>|</span>\\\n";
        } else {
            $imgs .= "<div style='float:left; margin:15px;'><a href='$imgdir/$subdir/$file'><img style='border: none;' src='$imgdir/$subdir/$file'/></a></div>\\\n";
        }
    }
}

echo $dirs;
echo $imgs;
?>

It's not elegant. It's not pretty. It has plenty of room for improvement - it'll generate links to Windows explorer thumbnail db's, etc... But it is fast and should be moderately secure. Just drop it in the root directory of your image structure and you're good.

Leave a Reply