Listing image files in folders and subfolders with PHP

Here's a quick way to create a listing of images uploaded to a folder with php:

<?php
// file name: list_pics.php

global $startDir;

/**
 * List Directories function, which transverses sub-folders
 * listing out the image files that exists within it.
 */
function listDir( $path ) {
  global $startDir;
  $handle = opendir( $path );
  while (false !== ($file = readdir($handle))) {
    if( substr( $file, 0, 1 ) != '.' ) {
      if( is_dir( $path.'/'.$file ) ) {
        listDir( $path.'/'.$file );
      }
      else {
        if( @getimagesize( $path.'/'.$file ) ) {

          /*
          // Uncomment if using with the below "pic.php" script to
          // encode the filename and protect from direct linking. 
          $url = 'http://domain.tld/images/pic.php?pic='
                 .urlencode( str_rot13( substr( $path, strlen( $startDir )+1 ).'/'.$file ) );
          */

          $url='http://domain.tld/images/'. 
          substr( $path, strlen( $startDir )+1 ).'/'.$file;

          // You can customize the output to use img tag instead.
          echo "<a href='".$url."'>".$url."</a><br>";
        }
      }
    }
  }
  closedir( $handle );
} // End listDir function

$startDir = '.';
listDir( $startDir );

?>

Use the below script to decode, encodeded filenames and display the image:

<?php
// file name: pic.php

$f = trim( $_GET['pic'] );
if( ( substr( $f, 0, 1 ) == '.' ) || ( substr( $f, 0, 1 ) == '/' ) ) {
  return false;
} else if( !( $imgType = exif_imagetype( str_rot13( $f ) ) ) ) {
  return false;
} else {
  switch( $imgType ) {
  case 1:
    header( 'Content-type: image/gif' );
    break;
  case 2:
    header( 'Content-type: image/jpeg' );
    break;
  case 3:
    header( 'Content-type: image/png' );
    break;
  default: 
    return false;
    break;
  }
  readfile( str_rot13 ( $f ) );
}
?>
Comment