Simple Dynamic Image Gallery using PHP

February 13th, 2008 by Jack Keller

So often you may want to show a little gallery of photos on your blog or website, you have a few choices out there. Choice one would be to just do a down and dirty bit of html, <img src=” etc etc or you could go with a program that creates galleries. Those usually don’t integrate with a site too well, and often are overkill for showing the world your new car, puppy or dinner entrees.

Luckily if you have your FTP program and a few pics handy you can just traverse your directories and spit out the files in code. This can be handy for swapping the files around and even adding more down the road, it will dynamically expand the gallery.

PHP:
  1. $path = “/home/user/public/foldername/”; //path from root
  2.     $dir_handle = @opendir($path) or die(“Unable to open $path”);
  3.     while ($file = readdir($dir_handle)) {
  4.         if($file == ”.” || $file == ”..” || $file == “index.php” )
  5.         continue;
  6.     echo ‘<img src="$file" /><br />’; //formatting this is up to you
  7. }
  8. closedir($dir_handle);

If you want to be slick, make thumbnails with the same name, but tag like tn_ before the image name and put them in another folder, this will allow you to call something like this:

PHP:
  1. echo ‘<a href="$file"><img src="otherfolder/tn_$file" /></a><br />’;

Note: This will also work for files, you can add options to filter only images if you’d like.

Share? These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • StumbleUpon
  • del.icio.us
  • NewsVine
  • Technorati
  • TwitThis
  • Google
  • Facebook
  • description

Posted in PHP

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

About media|extranet

We're a group of industry professionals who would like to give a little bit back to the community. Although we've just begun, we plan to do some write-ups on Advertising, Marketing, Development (.NET, PHP, Flash, Flex, AIR, JavaScript Frameworks, etc.) and Copywriting. Visit our contact section if you would like to see us cover something that we're not. The links below are for our writers, visit them directly if you have a project in mind that could utilize their talents.

Visit Snackbox Labs Visit ☆dup