Creating a simple image gallery with PHP & jQuery

An image gallery is a very common feature for a website to have. It is an efficient way to nicely present a set of pictures. With the increasing popularity of JavaScript plugin, image galleries are nowadays implemented with rich features, effects, and transitions, in order to emphasize the given content.

When you wish to create a picture gallery, there are several steps involved in the process. In this tutorial, we will see how you can set everything up, and then add, remove, or edit pictures in your gallery, in a simple and dynamic manner. Finally, we will explain how we can setup the jQuery lightbox plugin in order to work with our pictures.

What are the benefits of this solution? This methods is sooo easy to setup, but still achieves quite a lot. Little efforts, great rewards. You only have to put your images in a folder, and give that folder path to the class. You also tell the class how big you want your pictures to be, and it handles all the hard work for you. Just by calling a method, you can see your gallery on the page. So if you are looking for a fast and convenient way to put an image gallery on a site, read on.

Thank You for Downloading

I'm glad that you found my work useful. If you did, it might help some other people too. So why not helping me spread the word with a tweet? You could also buy me a coffee to thank me for my code and explanations if you prefer ;).
I hope you'll enjoy your download. Regards. Jeremy.

How to setup

The Plan of Action

To summarize what is covered in this article, here's a short list of the needed steps you need to take to make everything work:
  1. Put Your Images in a folder
  2. Include the files
  3. Change the variables to match your own
  4. Call the getPublicSide method
  5. Manage your pictures

Step 1: Put Your Images in a folder

As we are going to work with images, the first thing to do is to place your pictures in a folder on the directory structure of your site. When they are all uploaded, write down the path to this folder and go to step 2.

Step 2: Include the files

Let's have a look at the files you'll need to include in order to get the manager to work. You'll need six files: The jQuery Library, The imgallery PHP Class, javascript file and stylesheet, but also the LightBox script and styles in order to present the images very nicely:
  1. <?php
  2. //imgallery PHP Class
  3. include("Path_to/imgallery.php");
  4. ?>
  6. <!--Scripts (jQuery + LightBox Plugin + imgallery Script)-->
  7. <script type="text/javascript" src="Path_to/jquery.js"></script>
  8. <script type="text/javascript" src="Path_to/jquery.lightbox.js"></script>
  9. <script type="text/javascript" src="Path_to/imgallery.js"></script>
  11. <!--CSS (LightBox CSS + imgallery CSS)-->
  12. <link rel="stylesheet" type="text/css" href="Path_to/lightbox.css" />
  13. <link rel="stylesheet" type="text/css" href="Path_to/imgallery.css" />

Step 3: Change the variables

In order to work, the class relies on 3 variables, the folder path of where your pictures are stored, the size you want your thumbnails to be, and the maximum size of an image. In order to set those parameters, open the imgallery.php file, and change lines 23, 24 and 25 to whatever you want the configuration to be:
  1. //=======================================//
  2. //============> Constructor <============//
  3. //=======================================//
  4. public function __construct(
  5. $thumbsize = 96, //Change this to match your thumbnail size
  6. $maxsize = 640, //Change this to match your maximum image size
  7. $folderpath = "./lib/imgallery/pictures", //Change this to match your folder path
  8. $elements = array()
  9. ) {
  10. $this->thumbsize = $thumbsize;
  11. $this->maxsize = $maxsize;
  12. $this->folderpath = $folderpath;
  13. $this->elements = $elements;
  14. }
That's it, your gallery is pretty much ready to work now, you just need to open a page and to make a particular method call.

Step 4: Call the getPublicSide method

Now that you have changed your variables, the class is ready to get in action. If you are just looking for a quick way to make it work, open your page, and write the following:
  1. ImgGallery::getPublicSide();
By making this call, the logic behind the gallery gets your pictures from the specified folder. It then dynamically resizes your pictures and creates their thumbnail based on the given sizes. Finally, it displays the final result to the user, and sets up the LightBox navigation, ready to be used by your visitors. Wasn't that easy?

Code review

If you wish to know a bit more what is going on code wise, let's have a look together.
  1. //=========================================//
  2. //====> Easy call to set everything up <===//
  3. //=========================================//
  4. public function getPublicSide(){
  5. $gallery = new ImgGallery();
  6. $gallery->loadImages();
  7. $gallery->display();
  8. }
The getPublicSide method, creates an instance of the object imgallery. it then calls the method loadImages() to get the pictures from your folder, and the display() method to write the markup of the final result. As there's nothing extraordinary here, let's have a look at what happens next. The loadImages method calls getImageArray(). As you will see in the following code, getImageArray() uses the very handy php function glob in order to read the content of the given directory, and looks for images. Those images are then added to the gallery, they are now ready to be used with the object. As our pictures are ready, and loaded into the gallery, we then call the display method, which loops through the pictures, and for each of them, generates a thumbnail (done by the method getImageThumbnail), a resized picture (getMaxImage), and of course, generates the gallery markup.
  1. //========================================//
  2. //=====> List the images to include <=====//
  3. //========================================//
  4. public function getImageArray() {
  5. //Tell the class to look for images inside this folder
  6. $path = $this->folderpath . '/{*.jpg,*.gif,*.png}';
  7. $imgarray = glob($path, GLOB_BRACE) ? glob($path, GLOB_BRACE) : array();
  8. return $imgarray; //Return the found images
  9. }
  11. //=========================================//
  12. //==> Write the markup for the gallery <===//
  13. //=========================================//
  14. public function display($showit = 1) {
  15. $markup = '
  16. <div id="easyimgallery">
  17. <ul>';
  18. if (!empty($this->elements)) {
  19. foreach ($this->elements as $img) {
  20. $thumb = $this->getImageThumbnail($img);
  21. $maxsize = $this->getMaxImage($img);
  22. $imgname = end(explode("/", $img));
  23. $markup.='<li><a href="' . $maxsize . '" class="lightbox" title="' . $imgname . '">
  24. <img src="' . $thumb . '" alt="' . $imgname . '" />
  25. </a></li>';
  26. }
  27. }
  28. $markup.='
  29. </ul>
  30. </div>';
  31. if ($showit == 1) {
  32. echo $markup;
  33. }
  34. return $markup;
  35. }
That's it for the PHP side really. On the front end, the javascript files that we include are there to setup the LightBox plugin. It is just a simple snippet of code to say that every link that is found in the gallery will behave like a LightBox:
  1. jQuery(document).ready(function() {
  2. //Setup the lightbox
  3. $("#easyimgallery a").lightBox();
  4. });
At this point, the code is all ready to go. If you followed those simple steps and put your images in your folder, you should see the thumbnails appearing on your page.

How do I add, remove, or edit the pictures of my gallery?

As you now understand, the gallery works with a folder. As far as the gallery is concerned, it is this folder that holds all the information about your gallery. Based on this concept, if you want to:
  • Add an image to the gallery, simply copy it into your folder. The next time you refresh the page, it will be included.
  • Delete an image, simply remove it from your folder. The next time you refresh the page, it will be gone.
  • Edit an image of the gallery, simply rename it in your folder. The next time you refresh the page, the name will be changed.


This handy Class handles the coding of the gallery based on a folder path and image sizes. It's a simple solution that doesn't require a database in order to work, but that is still dynamic in terms of markup and thumbnail generation.

8 Responses to Creating a simple image gallery with PHP & jQuery

  1. This routine seems to assume that you are running from the root directory, since it places a '/' in front of the image directory for both the location of the thumbnails and the picture.
    For example, on my development system I am running from

    but the link to one of the images is:


    I hope that makes sense? I am looking at the display function in imgallery.php to see if there is a way to modify the incoming path. Is this the place to try to do this?

  2. I like it a lot! But I am wondering how the script orders the images... or more to the point, how can I rename the files so that I can control the order they appear in? (I've tried alpha-numerical order, that doesn't seem to work...) Any help much appreciated!

  3. thank you

  4. How can i put a variable in the place of folderpath
    just like this:

    • solved

  5. All files are not downloaded, (Ex : jquery.lightbox.js, lightbox.css)

  6. ImgGallery::getPublicSide(); which page do i open to write this code? am kinda confused/..

  7. Great post. I used to be checking continuously this weblog and I'm impressed!
    Very useful info particularly the closing phase :
    ) I maintain such information much. I was seeking this certain information for a very lengthy
    time. Thank you and best of luck.

Leave a Reply

Your email address will not be published. Required fields are marked *

Other Useful Resources

How to easily integrate a PayPal Checkout with PHP illustration

PayPal is a renowned payment platform that allows you to accept online payments on your site, by taking care of all the money transactions for you. This transparency really is an appreciated quality that allows developers to integrate checkout solutions on merchant sites, by completely outsourcing the banking operations to PayPal.

Another good thing for developers is that the PayPal API is very versatile. It can be very simple if your needs are simple, or it can be very well customized to meet some more advanced needs such as complete shopping carts handling. On the other hand, I sometimes find this API not really user friendly as it works with forms, which fields are not always very intuitive. In other words, depending on the form you are building, you get a different service from PayPal.

In order to get a friendlier and also more generic solution, I wrote a PayPal manager in PHP. This tutorial will show you how you can benefit from this PHP class to integrate PayPal checkouts faster and in a much simpler way.

Read more
A guide to Ajax Interactions with jQuery illustration

The fantastic jQuery library revolutionized the way javascript is being written around the globe. It's been globally acclaimed and adopted, resulting in an award for best open source project in the end of 2009.

In this article, we are going to see how we can use the power of this library to create your own Ajax request effortlessly, to make pages communicate in a user friendly way. Thank you jQuery team, the days of javascript darkness are over!

Read more
Scroll to Top jQuery plugin illustration

If you happen to have on your site some pages that are a bit long, and therefore will lead your users to scroll down quite a bit to read your content, they may not have the patience to scroll again to get back up to the top. That's where this little plugin, hand made by NOE interactive comes in handy. Just put it on your website, and it will help your users get back to the top of pages with a single click, and with a small smooth animation (how nice is that :) ).

In this article featured on NOE interactive, you'll learn how you can install the jQuery plugin on your website. There's a complete step by step guide as well as a demonstration. If you wish to download the plugin, it's also hosted on Github.

Read more
@Bentoutif Il occupe tout le monde afin que pendant ce temps on parle moins des résultats moyens de l'OL. A la Mourinho. Et ça marche.20 Sep / 09:12