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.

19 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. Wow, superb weblog format! How long have you ever been running a blog for?
    you made blogging look easy. The whole glance of your
    website is wonderful, as neatly as the content material!

  9. Thanks in favor of sharing such a nice thought, post is pleasant, thats why i have read it entirely

  10. Good web site . praca dla studentahere! Furthermore your web site so much right up very fast! Exactly what service provider think you're the application of? Am i able to 'm taking your online link on your own coordinator? If only the web-site jam-packed up as quickly when your own hehe

  11. That's it for my first article, when you have
    any questions go ahead and shoot me an e-mail at Danesheirhan@gmail.

    They aren't the same on the buildings as a result of different architectural
    styles. Hdmi to composite adapter walmart You will see watching videos, viewing documents or
    looking at photos exhilarating simply by connecting your media device into your Panasonic TH42PX80B.

    These wall plates have become affordable and still provide
    an excellent look. In addition to pay for channels, Roku supplies
    a broad variety of free content from channels for instance Crackle, PBS, Vevo, PBS Kids, TV Guide
    and NBC News.

  12. After short listing appropriate security safes, it can be
    a good idea to get hold of the manufacturer and clarify all of the
    details with regards to the safety vaults. You will be asked to penetrate this passcode when setting up your i - Phone.
    There are particular methods for handling Wi-Fi Security Cameras utilizing android rugged phones.

    The Black - Berry Bold 9700 Deals can also be uses an excellent home alarm system which will be the highlight in the Blackberry
    Bold, secure. For easy instructions on what to take off the Flygrip,
    see video here.

  13. One of my biggest lessons I learned from the Philippines,
    was around the language, and it turned out embarrassing.
    When cockatiels are cared for you will find certain habits that will show as a possible obvious signs
    of these contentment. Best. pussy For along with them for both Vaginal and Anal use,
    or even for sharing toys, silicone may be boiled safetly and 3-5 minutes of boiling
    will kill any germs.

    The town there we were heading to, was famous to get a
    game called "smiles". The more pressing dilemma is whether finally the Congressmanny has overloaded his plate with regard to nonboxing
    matters.

  14. The embarrassment employing such products could be mitigated by attending an exciting party and also
    ordering whatever you need in the comfort of your
    individual home. Now talk for the Mole Man inside room and judge
    the daughter option. How to make pussy toy They feel gorgeous and wonderful, and
    mood is normally upbeat.

    This is since the pleasure that may be experienced because of the woman utilizing a rabbit vibrator is beyond comparison. You can lay there and continue to enjoy your encounter, but what happens if you just can't.

  15. Overall it's very an amazing Blu-ray Disc Player, that may handle any kind of Discs you throw in internet marketing,
    with optimal performance. If you desire a cable more than 4,5m, you'll should consider the
    premium quality cables. Rca female to hdmi I'll present you with a quick breakdown of how the G155 Mobile Gaming System
    will probably change how gamers travel.

    These files could be played back within the BDP-93 with the two USB Ports or perhaps the e
    - SATA Port located for the back. Cons: Mediocre viewing angles; Minimal scope for height adjustments;
    Weak speakers.

  16. Finish the lesson by telling the children around the Montgomery bus boycott, and
    telling them that Rosa inspired others to square up
    towards the unfair laws. This band was part from the "Beautiful Noise" scene on the early
    1990's. Pocket pussy sex toy I got your little friend remote and gave the concept a press.

    The adult entertainment happens to be one in the fastest growing and a lot robust industries around.

    or disheartened as long as they can't satisfy their woman from intercourse.

  17. Understand extra about acquiring the most from your play with the following article.

  18. Winning back your girlfriend needs you to develop something first: need and yearning.

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
How to integrate your instagram pictures with php illustration

Ever looked for a straightforward way to integrate you instagram pictures on your website? Without a plugin nor an iframe? Well this article featured on the NOE interactive's blog presents how you can do so with PHP.

It's a neat and simple solution that uses the instagram's API to get a particular users' latest pictures, and then display them in a ul list.

It is accessible to most developers as it is a "personalize, copy and paste" kind of solution. Just two steps are required, configuration, and implementation.

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

Read more
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
@NightVlewer obligé. Je n’aurais mm pas misé 30ct dessus. 😫24 Mar / 07:23