Simple Dynamic Image Gallery using PHP

February 13th, 2008 by Jack Keller

So often you may want to show a lit­tle gallery of pho­tos on your blog or web­site, 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 pro­gram that cre­ates gal­leries. Those usu­ally don't inte­grate with a site too well, and often are overkill for show­ing the world your new car, puppy or din­ner entrees.

Luck­ily if you have your FTP pro­gram and a few pics handy you can just tra­verse your direc­to­ries and spit out the files in code. This can be handy for swap­ping the files around and even adding more down the road, it will dynam­i­cally 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 = read­dir($dir_handle)) {
  4.         if($file == "." || $file == ".." || $file == "index.php" )
  5.         con­tinue;
  6.     echo '<img src="$file" /><br />'; //formatting this is up to you
  7. }
  8. closedir($dir_handle);

If you want to be slick, make thumb­nails with the same name, but tag like tn_ before the image name and put them in another folder, this will allow you to call some­thing 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 fil­ter only images if you'd like.

Share?
  • Facebook
  • Design Float
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Digg

Posted in PHP Be the first to comment! »

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