Image Gallery from a Directory using PHP

So you have a directory full of images, and you want to turn it into an image gallery for everyone to see. Yes! You can have nice little organized gallery using database, which of-course involves entering lengthy data into records. But what if you can quickly create an image gallery using few lines of code? The PHP snippet below can be used to achieve the same. You can just drop this PHP snippet within the body of your HTML code, using some CSS and Javascript it can create nice looking image gallery. Or you can use this script to automatically enter image records in database.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
<?php $folder_path = 'images/'; //image folder path $folder = opendir($folder_path); while (false !== ($entry = readdir($folder))) { if ($entry != "." && $entry != ".." && $entry != "Thumb.db") { $file_path = $folder_path.$entry; $ext = strtolower(pathinfo($file_path, PATHINFO_EXTENSION)); if($ext=='jpg' || $ext =='png' || $ext == 'gif') { echo '<img src="'.$file_path.'" />'; } } } closedir($folder ); ?>
Here's another one using PHP glob(). But it can be bit slower than above example, because it scans sub directories and parses the arguments.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
<?php // display source code $folder_path = 'images/'; $files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE); foreach($files as $file){ echo '<img src="'.$file.'" />'; } ?>
New question is currently disabled!