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. ?>
  5.  
  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>
  10.  
  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. }
  10.  
  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.

Conclusion

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.

13 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
    http://localhost/jQueryGalleryAndSliders/SimpleImageGallery/index.php

    but the link to one of the images is:

    http://localhost/images/cache/640x480.~images~filename.png

    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?
    Thanks!

  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:
    $folderpath=$dir,

    • 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.

  8. Ⲏі! I could ave sworn I've Ьeen to this
    website ƅefore but after ϲһecking thrⲟugh some oof the
    post I realized it's new to me. Νonetheleѕs, I'm definitely
    glad Ӏ found it аnd I'll be book-marking and checking back frequently!

  9. Hi there colleagues, good article and fastidious arguments commented
    at this place, I am actually enjoying by these.

  10. I die ganze Zeitt mailote diese Website Post-Seite, um
    allle meine Freunde Kontakte, , weil, wenn es gerne
    lesen vvor Kontakkte auch.

  11. First let me say thank you this was extremely helpful.
    I also have a question:

    Would it be possible for you to added a little more advanced version that adds paging instead of just loading all the images?

    Thank you

  12. hi I'm currently creating a website for some friends and i would love to use these scripts in order to make my photo gallery more responsive with a faster load speed.

    Its in the Photogallery page which I'm trying to achieve the above.

    Regards

    Steve

Leave a Reply

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

Other Useful Resources

How to integrate the new Twitter api (1.1) in php illustration

On October 11th 2012, Twitter introduced some major changes in its API following its plans to clean things up deeply. As is explaining the twitterapi account they have for example shut down or limited access to some of their data and resources. So if you've noticed that some Twitter functionalities you are using on your site are not working any more, you may have to check a few things. In this article written on NOE interactive's blog, you'll learn what has concretely changed, and you'll be able to follow a few steps to get your Twitter feeds back.

Read more
Retour sur Blend Web Mix 2015 illustration

Blend Web Mix, c'est la conférence Lyonnaise du Web. C'est une chance d'assister à des des conférences enrichissantes et motivantes, de rencontrer des gens intéressants, le tout dans le cadre toujours très agréable de la cité internationale. Cette année encore, l'édition a été riche en enseignements. Retour sur les conférences auxquelles j'ai assisté, et ce que j'ai pu en retirer.

Read more
How to make SEO friendly urls illustration

It's now quite common to swap the old url format containing file extensions and non explicit query strings by SEO friendly ones, only made of keywords and slashes, hence their name.

There are several techniques to do so, and I certainly do not have the pretention to say that this one is the best of all, but it is the one I use in personal projects as it works nicely, and it is robust and dynamic.

It makes use of an .htaccess file to rewrite the urls, of a php function to parse the given parameters, and a content manager to serve the appropriate content according to them.

Before we start I'd like to make a personal thanks to Josh Moont for his precious help.

Read more
That's why I still use a mix of ES6 classes + jquery. That ticks all my criterias. Wondered if there was something more "modern" #lasttweet15 Sep / 10:34