Create an Awesome Photo Gallery with FancyBox and TimThumb

Time for a little tutorial eh? Let’s make a Photo Gallery – one that is a combination of already made scripts and plugins; one that is loaded automatically; and of course – one that looks awesome. We are using PHP, FancyBox jQuery plugin and TimThumb.
Important: You should use the latest version of TimThumb due to vulnerability issues with old code. Make sure you keep updated to keep your site secure.
Ready to get started? Let’s begin:

Set up the Environment:

In order for our PHP scripts to run, you need to have a web server. A good example is XAMPP, which is free and can be downloaded from http://www.apachefriends.org/en/xampp.html. Create a root folder – name it anything, and inside it, create the following folders:

  • Images – this is where the image of the gallery will go.
  • Scripts – this is where our scripts will go

Download Timthumb script: http://www.darrenhoyt.com/2008/04/02/timthumb-php-script-released/. Timthumb is an image resizer script that is written in PHP. Save timthumb.php inside scripts.
Let’s create a new HMTL file inside the root, name it index.php. Add this line of code:

The above code creates 2 variables:

  • $path – is the full image path of our images
  • $files – is an array of filenames from a specified folder that we’ve scanned through the scandir() function

Then add the code below:

This loops through each item in the array $files – and assign it to another variable $file. For each one found, we’re printing a list item with an anchor and image tags. Within these tags you’ll notice the variables we’ve created earlier. The timthumb script is inserted at the beginning of the src attribute of our thumbnails. The width and the height parameters are hard coded in there as well. Note that we are going to randomize this section a little bit later.
Assuming that you already have photos in your image folder – fire up your web browser and navigate to index.php. You should have something like the screenshot below:

As you can see – we’re swiftly on our way. Our thumbnails are resizing right. Once clicked, the larger image appears. Though there are mysterious images that are returning empty (file name is shows as “.” and “..”). This may not be the case with yours – but with me, I just decided to fix this by wrapping our list items inside an ‘if – else’ statement:

Now we move on to the Fancy Box script:

Add Fancy Box

I almost always use jQuery for all my projects. It is one of the most versatile and powerful javascript libraries to date. Download the latest version from http://jquery.com/ and include it in your document.
Download the Fancybox files from http://fancybox.net/. Once again, include the script right under the jQuery one. Note that Fancy box comes with its own image folder and css file. You need to include that css as well:
Now let’s add a “rel” attribute to our anchor tag, with a value of “lightbox”. This makes it easier for our script to target which elements to add an effect on.
Finally, create a new script tag and add our line of code:

The above code states that when the document is ready – grab all the anchor tags with an attribute value of “lightbox” and hook it up with the fancybox function. I’ve chosen the effect ‘Elastic’ for the transitions – you can replace this with your own liking.
Now go back to the browser and hit F5 to refresh. Click on a thumbnail – you should see Fancy Box in action with smooth and eye popping animation added to your photo gallery.

Next up – some styling with CSS.

Pretty ‘er up.

Now it is always good practice to separate your formatting and markup. Create a new file named style.css, go back to index.php and link the stylesheet we just created.
In the last screenshot you notice that I marked the little buttons. That’s because of two things – if you’ve configured Fancybox correctly – those icons should be visible. The other thing is, I’ve created an icon that is very identical to those of Fancybox’s – and we’ll include in our thumbnails. Take a look at the couple of images below:

These images (available in the download) I’ve saved inside the root folder. In your style.css – add these lines of code:

The code above adds a nice texture to our gallery background. Next, it floats each item to the left – aligning them all side by side. Then it adds a nice white background to each image, along with proper paddings and margins:

Remember our custom script tag just above our closing head tag? – add, this line of code just in between the $(document).ready() function:

This will insert an empty span tag inside each of our list items (this is for the small magnifying glass icon). If you’re thinking – why not just add an inline span tag in our “for each” loop inside index.php – that’s an excellent question. This is because for users without javascript enabled – they won’t see this magnifying button.
Add these lines of code inside our style.css:

The above styles adds the subtle details that will make our thumbnails beautiful. This includes – of course our magnify.png, CSS3 box shadows (box-shadow) and rounded corners (border-radius).

Our gallery looks really good so far, but not good enough. Let’s add some embellishments.

Randomize the Images and Orientation:

Let’s make the thumbnail images be mixed orientation – some tall and some wide. Remember our thumbnail dimensions declared right after the timthumb script? All we need to do is switch the height and width values. So let’s create a PHP function. Append this code on top of index.php (right before the html tag):

The code above randomizes the two strings (‘&h=194&w=224‘ and ‘&h=224&w=194’). Then we call this function where our image tag is:


Now our thumbnails have different orientation each time we refresh. But as you can see, we need to fix the float – some thumbnails get stuck where portrait ends. We also need to fix the magnify icon positioning.
We need a way to tell what the current thumbnail orientation is, and somehow apply a class to that specific list item. This way we can fix the padding and margins accordingly. Add this line of code inside our “else” statement:

This grabs the current orientation and assigns it to a variable. Now, inside our li tag – paste this line of code:

This adds a class name of “tall” for each list item – if the $current_o variable equals to the portrait dimension. We also need to replace our image thumbnail script to this new code:

Refresh your browser and if we inspect our code – you should see list items with a class of “tall” for images that have 224 x 194 dimensions:

Also, add these lines of code to our style.css file:

The above code overrides the default styling for the list items.
Note that you also have to delete some previous styling for our list items (see the comments in the download). If you’re following this tutorial – I apologize for the replacements. As you see, I’m developing this as I go.
Lastly, add this code inside index.php:

This will randomize the images. So now we’ve fixed the list items, magnify icon – as well as randomized the images:

Final Touches:

So our gallery is so done. Except I like to add those final details that make it really good. Let’s add a pre-loader image. This is when you see a “loading” message for each thumbnail before they appear. To do this, we go back to jQuery. Inside our document ready event, add this line of code:

The above code delays our images just a tad bit – just enough to see a preloader image. Save your “loading.png” image in the root directory. In your styles.css, add these lines of code:

This just sets a background image to our list items. So next time you load the page – you should see our preloaders:

Finally, download the fancy box mousewheel.js pack inside your scripts folder and include it in your document. You should now be able to view next and previous images once you scroll your mouse wheel.

Conclusion:

Well now, I think our gallery is ready for prime time. The good thing about this is you never have to re-size a thumbnail again. All you need to do is add the large image inside the “images” folder and presto! Another good thing is that your gallery doesn’t look the same all the time. With our randomized order and orientation, the gallery looks fresh at each refresh. So go ahead and grab the download files. Play around with it – and maybe even improve the code. Be sure to include your comments below:

64 Comments

  1. Wow, my head is swimming after this one! One question I have is in regards to the magnifying glass icon. I kept wanting to click it but it’s just there for show it seems. This is on Chrome v. 10.x BTW. Is that intended behaviour for the icon?

    Reply
  2. Hi,
    and thanks for this wonderful tutorial!
    I wonder how you can make this into a web page containging multiple galleries. I’m a complete noob when it comes to web pages, can you please gice me a hint?

    Reply
  3. Thank you so much! I’ve been trying to teach myself “just enough php” to do just this, with the customary ensuing frustration—With this you’ve zoomed my project ahead lightyears in one short evening! I will repost the site url once it’s done. Again, many thanks!

    Reply
  4. Hello, thanks for that good work.
    I just have a little prob : when I click the thumbnails I have this message “The requested content cannot be loaded.
    Please try again later.”.
    I had made all the tuto as explined but when I opened the source of the online page (index.php) I saw a strange error where the path is repeated twice ::
    I don’t see the error I made may be here :
    I stay blind… sorry for my english and thank you for your response.

    Reply
  5. This thing is awesome! I connected it to my database and using string variables in the paths I can launch seperate galleries by user id (much like FB & Flicker do). I’m working on a good up-loader and user script for this. It’s just what I needed for a new project I am working on. Have you considered pagination? some of my folders are pretty big.
    On one host it works perfect but timthumb flops on the other even with the latest version. Haven’t figured that one out but it’s working great on the other. I can’t wait to get the rest of my app set up. Thanks for a really useful script.

    Reply
      • Ok so I took this and ran with it. in the end I changed a lot of stuff but this tutorial inspired me. First thing is that I have a lot of photos so i either had to have a lot of folders or go another way. What I did is set up a database with two tables, one for images and another for categories. Then replaced the Tim thumb script and used the gd libraries re-size functions. I upload my images and they are sized exactly as in the tim thumb, as well as a 900px max width or height version and the original. So I have 3 images for each photo. My up-loader renames them all so I never worry about overwrites. Then using the “get” function I call the modified page from here and there it is.
        I did away with the randomization because I have pagination that shows 20 images at a time in order. This turned out extremely well and was the result of no less than 4 tutorials and two weeks work. I still haven’t cleaned up the code well enough to suit me but it is working without any issues. Thanks for a great tutorial.
        Here is the outcome. http://social-widget.com/gallery1/viewgallery.php

        Reply
  6. If the image folder contains a subfolder, the script scans it as it was an image and it displays it as a broken image link. How can I exclude subfolders from scanning?

    Reply
    • you would have to create an array of subfolders to be excluded and change the loop from a foreach to a for. something like below:

      <?php
      $exclude = array('images/folder1', 'images/folder2','images/folder3' );
      for($i=0; $i<count($files); $i++):
      ?>
      <?php if(!in_array($files[$i], $exclude)){?>
      <li><a href="<?php echo $path . $files[$i]; ?>"><img src="scripts/timthumb.php?src=<?php echo $path . $file[$i]; ?>&h=134&w=264&zc=1&q=100" /></a></li>
      <?php}?>
      <?php endfor;?>

      Reply
  7. This is a tough guide for someone who never done any php coding.
    I got as far as to create a root, image and a scripts folder. However my pictures show up as broken, which makes me assume i have done something wrong in the first steps, but i can’t figure out what. Also there appears to be more images than i have in my folder.
    I also can’t figure out what document to include jQuery in.
    I think if i had more knowledge on Php this would be a easy guide.

    Reply
  8. I have thought about my issue so much that my brain hurts, i can’t figure out what i am doing wrong.
    Im still at step one.
    It lists all my pictures as broken thumbnails, but when i click on them it opens op the pictures.
    Im suspecting something is wrong with this line:
    $path = ‘http://’ . $_SERVER[‘SERVER_NAME’], do i have to alter something here? or does ‘http’ and [server_name] just have to stay unaltered?
    It might be something else, but i have no clue to what it could be.

    Reply
      • Hi Michael,
        I solved my problem. It wasn’t due to any coding. My problem was with the image folder and it’s permissions. Once i changed that, everything worked! 🙂

        Reply
      • Yet another obstacle occurs! 🙁 Hopefully the last related to creating this php gallery.
        As it is right now, all the small thumbnails show up on index.php. But when i click on it, it just opens the picture up on the following page. Take this as an example: http://demo.fearlessflyer.com/html/demo/photo-gallery/images/1255126_50122408.jpg
        For some reason the fancybox script is not working, and I’m pretty sure that the code is correct, and I’m also doubting that permission is what causing the problem.
        This is the destination where my scripts are located and are named.
        src=”scripts/jquery-1.7.1.min.js”>
        src=”scripts/fancybox/jquery.fancybox-1.3.4.js”
        Any coiners as to what i am doing wrong?

        Reply
      • Scratch that. After hours of checking, rechecking and double checking i finally got it to work!
        This time i honestly don’t know how i fixed it. All of a sudden istead of images opening in another window, they opened up in the bottom of the page. From there i figured out another problem, i had placed the fancybox css in a wrong folder. Once i put the css file in the right place, everything just worked.
        But i am very curious as to how i solved the first problem!

        Reply
  9. Is there a way to create thumbnails for sub folders? Im looking to incorporate what Len created but with thumbnails with text vs just text or just the thumbnail.

    Reply
  10. now I kinda solved my problem.. if I echo out $path i get the right url but it shows destroyed images.. If I click on them it does work. What have I done wrong??

    Reply
  11. Please help me! What can I have made wrong, I have study php, mysql and html in at least 3 years but I don’t get my images to show up at the first step. I need your help very much this is the best gallery on the web that you learn out! I love your tutorial but what can I have made wrong?? Please help!

    Reply
    • File and folder permissions should be set on 777 (read-write-execute for everyone) for cache directory and its content. I had the same problem before on localhost. However when I uploaded the code on the web server I had no problem with the permission. You can change permissions when cache directory is created. Go to mkdir(cache) (or something like that) in timthumb.php and you can change it like this mkdir(cache,0777). I put the 0 in front because the mode should be in octal. Or just use chmod. Hope this works for you.

      Reply
  12. Very helpful tutorial..
    Thank you.
    but i have a problem with the thumbnails… they are not apear. but when i click on them it leads me to the original photo.. what should i do??

    <a href=""><img src="scripts/timthumb.php?src=&h=194&w=224&zc=1&q=100" />

    this is the code

    Reply
  13. Hello,
    I am trying to use your system. I can get the thumbnails to appear, but when I try to use the latest versions of jquery and fancybox, the effects are not showing up (nothing changes). I am using jquery-1.7.1.min.js and fancybox v. 1.3.4. I have followed your instructions exactly, and yet it is not working. Also, when I include the extra rel=”lightbox” in the path name, the thumbnails show up, but when clicked the pictures do not citing an error. This still does not make the fancybox effects appear. Please help me if you can. Thank you.

    Reply
  14. I would like to have a gallery with the same image order all the time, so i removed the randomization code. The problem is my images aren’t all the same size, and i would like to have tall and wide pictures, according to the origional picture size.
    Is there a way to recognize the ratio of a picture, and then giving it either a tall, or a wide picture frame based on the ratio?

    Reply
  15. whoa.. I was playing with timthumb so far but i found great tuts of create an awesome photo gallery using timthumb, you know, I was stuck on creating a gallery.. thanks for your share man

    Reply
  16. i’ve been looking at how to create a photo gallery for ages via php and this is the best one i’ve come across! the only problem is when i try to view the sample to test it via easyphp it doesn’t work, just shows the loading part… no images are actually shown, any help please? cheers!

    Reply

Leave a Reply to Len Farneth Cancel reply