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:
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?
yes its just for show.
Great tut after a long while 🙂 . looking forward to see more tuts !
How do we incorporate this gallery into a WP site and/or do any of your wp site have this?
it would have to be converted into a plugin
Sounds like a job for you 🙂
I think my theme developer uses a lot of this:
http://elegantthemes.com/
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?
multiple galleries – just duplicate the pages, have scandir() in a separate directory.
I included everything and it seems to work fine. But some thumbnails are not loading. Out of 44 images only 18 thumbs are showing up. Am I doing something wrong? Please check out the site I worked on here… http://ausdegree.com/kite-surfing/gallery.php
it looks like you got it. awesome gallery.
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!
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.
I’m sorry … the code is not allowed,
well in the source of the index page I have in the “img src” that error : http://www.prestipedia.netwww.prestipedia.net/photo-gallery/images/Image8.jpg
My path is :
path = ‘http://www.prestipedia.net’ . X_SERVER[‘SERVER_NAME’] . ‘/photo-gallery/images/’;
Hope that is allowed … lol
Only 7 thumbnails apears for me…
nevermind, it was because I forgot to resize my images
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.
Hi Len, please share version of what you made out of this tutorial or at least some pointers.
Thanks alot
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
Awesome work Len. Now I want to revise the tutorial to include your mods! Thanks for sharing
Hi, can you describe how to disable randomization?
you should skip the section to randomize the sizes and the order.
Wow now thats WORK, thanks for the pointers.
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?
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;?>
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.
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.
do an echo $path and see if if looks like your web server url. i.e. if its http://localhost/ etc.
Im sorry, but i need a little more elaboration than that. Im a real beginner when it comes to PHP.
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! 🙂
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?
make sure the scripts are being included in the page.
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!
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.
Hi,
Great tutorial, working great, thanks.
But wondering how to make the magnifying glass icon a link to the zoom view?
Any ideas?
TIA!
yes. you can add an anchor tag inside that empty span – with href to the larger image.
I need help! I cant get what i should put in
It was a lagg, I dont know what ishould put in the $_server[andthisbox]
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??
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!
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.
thanks Vlad
hi ..i am try to add this in wordpress theme .. but problem is the zoom icon in widget .. can you help me ..
the zoom icon – you might want to use firebug to inspect the html. it will help you out.
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
tha php code for above msg
<a href=""><img src="scripts/timthumb.php?src=&h=194&w=224&zc=1&q=100" />
it looks like you don’t have correct permissions for the cache folder. check inside scripts folder – cache should be writable
problem with the page is http://www.sarvajanikhighschoolukhalda.org/testgal.php
plzzzzz help me
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.
Correction…it works in Firefox fine, but does not work in Chrome? Do you have any idea why this is?
Ok, for some reason it wasn’t working, now it is. But certain pictures won’t have thumbnail pictures appear, even with the if statement included. They are regular .jpg images (although quite large). Is there a size limit with this system and a way to change it?
yes i believe there is a size limit. I’m not sure what it is though – ck timthumb’s documentation – http://www.binarymoon.co.uk/projects/timthumb/
try installing firebug to see the js errors. if its something like ‘undefined’ or ..is not a function – that means its not finding the functions correctly. make sure rel=lightbox is captured by testing it out – do something like
$(a[rel=lightbox]).click(function(){
console.log('clicked');
})
I would love to use this beautiful gallery but nothing comes up except the top sentences. It’s a static upload of your sample and I’ve already checked my file and folder permissions. What else could it be? Any help would be great:
http://www.pixelbiz.com/clients/DWB/photo-gallery/
php installed?
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?
im sure you can do it in javascript. detect each image’s width and height and apply changes to it.
http://www.cssonly.nl/zaagfiguur/index.php
Try to fix this site for my dad, but it doesnt work well.
Can someone please check this out?
I need a photo gallery and it seems that this is a good solution.
I suppose the *.js scripts arent loading well?
http://www.cssonly.nl/zaagfiguur/index.php
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
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!
Can I add Disqus to each picture?
thank you very much < i will try to learn from your files