How to make Photo Gallery from image Directory with PHP

Are you faced with the task of organizing a large collection of image files into a visually appealing PHP photo gallery? There are the following solutions that you can use:

Solution 1:
One approach to creating a photo gallery is to manually add each image file to your web page individually. However, this method proves to be time-consuming and cumbersome, as it requires constant monitoring for any future updates to the image links.

Solution 2:
Another option involves storing the image names in a Database table and retrieving them when needed. This solution offers more efficiency and flexibility compared to the previous one.

Solution 3:
However, the most optimal solution involves reading all the files from your designated directory and generating an automated photo gallery. This approach eliminates the need for manual intervention and ensures that any changes or additions to the image directory are automatically reflected in the gallery.

In this post, I will focus on demonstrating the implementation of the third solution, utilizing the power of PHP. By following this guide, you will be able to create a dynamic and seamless photo gallery effortlessly.

So, without further ado, let’s dive into the exciting world of PHP photo galleries and discover how you can transform your image directory into an engaging visual experience!

How to make Photo Gallery from image Directory with PHP


Table of Content

  1. Download and Include simplelightbox library
  2. HTML and PHP: Create Photo Gallery layout
  3. CSS
  4. jQuery: Gallery Integration with SimpleLightbox
  5. Demo: See the PHP Photo Gallery in Action
  6. Conclusion

1. Download and Include simplelightbox library

  • I am using simplelightbox jQuery library for making the gallery that you can download from here.
  • Include simplelightbox.min.css and simple-lightbox.jquery.min.js.
<link href='simplelightbox-master/dist/simplelightbox.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="simplelightbox-master/dist/simple-lightbox.jquery.min.js"></script>

2. HTML and PHP: Create Photo Gallery layout

Reading files from a directory with PHP.

  • I am reading files from images the directory which also has sub-directory thumbnail.
  • The directory and file structure looks like this –

How to make Photo Gallery from image Directory with PHP


Specified valid image extensions in the  $image_extensions Array variable and target directory in $dir.

Read all files from the directory and set thumbnail and image path.

If it is a valid image and not a directory then use the path in the image source.

I only use $count variable to show 4 images in a row.

<div class='container'>
    <div class="gallery">
 
        <?php 
        // Image extensions
        $image_extensions = array("png","jpg","jpeg","gif");

        // Target directory
        $dir = 'images/';
        if (is_dir($dir)){
 
            if ($dh = opendir($dir)){
                 $count = 1;

                 // Read files
                 while (($file = readdir($dh)) !== false){

                      if($file != '' && $file != '.' && $file != '..'){
 
                            // Thumbnail image path
                            $thumbnail_path = "images/thumbnail/".$file;

                            // Image path
                            $image_path = "images/".$file;
 
                            $thumbnail_ext = pathinfo($thumbnail_path, PATHINFO_EXTENSION);
                            $image_ext = pathinfo($image_path, PATHINFO_EXTENSION);

                            // Check its not folder and it is image file
                            if(!is_dir($image_path) && 
                               in_array($thumbnail_ext,$image_extensions) && 
                               in_array($image_ext,$image_extensions)){
        ?>

                                <!-- Image -->
                                <a href="<?php echo $image_path; ?>">
                                    <img src="<?php echo $thumbnail_path; ?>" alt="" title=""/>
                                </a>
                                <!-- --- -->
       <?php

                                // Break
                                if( $count%4 == 0){
       ?>
                                     <div class="clear"></div>
       <?php 
                                }
                                $count++;
                            }
                      }
 
                 }
                 closedir($dh);
            }
        }
        ?>
    </div>
</div>

3. CSS

.container .gallery a img {
    float: left;
    width: 20%;
    height: auto;
    border: 2px solid #fff;
    -webkit-transition: -webkit-transform .15s ease;
    -moz-transition: -moz-transform .15s ease;
    -o-transition: -o-transform .15s ease;
    -ms-transition: -ms-transform .15s ease;
    transition: transform .15s ease;
    position: relative;
}

.container .gallery a:hover img {
    -webkit-transform: scale(1.05);
    -moz-transform: scale(1.05);
    -o-transform: scale(1.05);
    -ms-transform: scale(1.05);
    transform: scale(1.05);
    z-index: 5;
}

.clear {
    clear: both;
    float: none;
    width: 100%;
}

4. jQuery: Gallery Integration with SimpleLightbox

Initialize simpleLightbox by calling simpleLightbox() method on <a> of gallery class.

<!-- Script -->
<script type='text/javascript'>
$(document).ready(function(){

    // Intialize gallery
    var gallery = $('.gallery a').simpleLightbox();

});
</script>

5. Demo: See the PHP Photo Gallery in Action

View Demo


6. Conclusion

Creating a PHP photo gallery from an image directory offers a practical and efficient way to organize and display your image collection. Simply specify the folder location where your images are stored, and the PHP script will handle the rest, automatically skipping any non-image files it encounters.

Additionally, you have the flexibility to customize the gallery layout by utilizing other jQuery libraries.

With this knowledge, you can easily create a captivating and dynamic photo gallery using PHP, showcasing your images in an appealing manner to your audience.

If you found this tutorial helpful then don't forget to share.

65 thoughts on “How to make Photo Gallery from image Directory with PHP”

  1. Would be awesome if you could read the photo description from a text file. Would be good for SEO and you could add the description to the photo viewer.

    Thanks for the TUT, i put it on my CV site. http://joshpetersen.me/pics

    I modified the CSS to fit all images in the frame so nice and tidy.
    object-fit: cover;
    height: 10vw;

    Reply
  2. Hi,
    could you show us how to dynamically add new photos to the gallery? I got a Photobox and a want to use this gallery on my webserver. If new photos are in the images folder i want to see them in the gallery too.
    Best
    Jens

    Reply
  3. Dear Sir,
    I found your gallery maker on the web.
    I like it very much but there are a few things I seem not be able to control.
    1. some pictures are not displayed in the correct orientation.
    2. I do not understand the sorting. The pictures are not displayed in the order of the directory. To me it is like it is a random sort!
    Maybe you can give me an indication how I can control the orientation and the sorting.

    Greetings, Ad van Rossum

    Reply
    • 1. To fix this you can set the height of images.
      2. For example, if you want to sort according to image name then use Array. Create an associative array and initialize it with thumbnail path and image path while reading files. You can get image name from the image path by extracting it.

      e.g. $images_arr[‘imagename 1’]= array(‘thumbnail’=>$thumbanil_path,’image’=>$image_path);

      Now sort the array by key ( image name ) using arsort() and loop on it to create images.
      I hope helps.

      Reply
  4. Do you mean somethin like this”?
    <a href="”
    <img style="max-height:40px;max-width:80px;height:auto;width:auto"
    src="” alt=”” title=””/>

    This had no effect on orientation only made thumbs smaller!!

    Reply
    • Hey Chad,
      To see it in action you need to install PHP on your machine. I have installed apache2.4 and php (it took me hours to set it up). Using localhost setup i can test any php code and MySql database(You need to install mysql also for database, no need to install if you are not dealing with databases).
      When it comes to website hosting they (most of service providers) already have these installed. So if you own a website than you can simply upload it to filemanager/public_html and you are good to go. No need to install and setup anything.

      Reply
  5. Hi,
    Downloaded all codes however not getting desired result. Please have a look of “https://sarojsymphonysociety.co.in/gallery.php” and suggest the update.

    Reply
  6. actually i want image gallery like this , but want to download a file related to it. for example I will show a chair model image loaded automatically and when clicked it should download a zip file which has the 3dmodels and related to it can it be done with this script

    Reply
  7. Hey,
    Thanks for the script. Very useful. Just a few (minor) comments/suggestions (although I am not sure you keep this as a continuous development?):
    – in your PHP list of accepted file-types, it would be useful to add the same ones in uppercase (many cameras have all filenames in uppercase by default …);
    – to have no sorting is a bit tedious. I have seen your previous comment, which allow for many sorting options, but you also could use Scandir. However, for somebody who is not a PHP programmer it is a bit difficult to modify the script. A workaround is to upload the files one by one, instead of as a batch. In my case, my server default is that they are sorted by time of upload (so PHP takes that order).
    All the best,
    P.

    Reply
  8. and now i see the big download purple button…
    Tx for your answer, I’m downloading it right now
    I’ll give you credits in the code

    Reply
  9. I hope it’s ok to ask questions?

    Everything is working well but when I click on a picture, i don’t have the effect as in your demo where the picture is showed over the gallery and there is 2 arrows and a X to close the picture

    In my case, it open the picture on a black background and there is nothing to do from there (no arrows or X)

    I’m missing something?

    Reply
  10. Umm… I have a problem with implementing it.
    Not sure if I am putting the code in the wrong place or what, but while the script seems to work fine, it doesn’t upload any image and just leaves blank html image spot.

    lightbox included – check
    folder structure – check
    gallery div with php placed in the body of html – probably wrong?
    css inside css file – check
    jquary script initialization – behind php script?

    Reply
  11. Hi, I really love this photo gallery! Thanks for sharing!
    Could it be that the closing action of the gallery is not supported by all browsers and/or browser versions? On one macbook I can use the close button, on my other I can’t, on mobile I can. Do you have any suggestions?

    Reply
  12. Hi Yogesh,
    I’ve downloaded your example and have some remarks and questions :
    as I launch index.php on local server the thumbnails are not displayed, only empty squares ???
    but as I click on one, all run well, I see the big picture and the gallery runs …
    I’ve put small pictures in /thumbnail/ dir … nothing appears
    – why are the thumbnails unvisible ?
    – does this php create the thumbnails ?? I’ve tried without any file in /thumbnail/ dir , same result !
    – how can I block downloading capabilities by right-click ?
    and … a great Thank You for your article
    cheers
    Christian

    Reply
  13. Hi, this is a nice script, but not much use for many images without sorting by name, is there a chance you could add this please?, thank you

    Reply
  14. Very useful thanks! quick questions:
    1) how to best generate thumbnails for 100 pictures?
    2) any way to do it programatically?

    Thanks!

    Reply
  15. I ve tried your PHP solultion, it works very nicelly for me, thanks. I higly recommend putting after last image. It helped me properly style gallery.

    Reply
      • I noticed the gallery section in the style.css file already has margin: 0 auto in your source code. I also tried adding margin: 0 auto to all sections in style.css and the style sheets in the lightbox folders and was not able to center the gallery.

        Any help would be greatly appreciated and I’m sure others would like to do this as well 🙂

      • Hi I don’t have a live link since i am running test on local apache server. Could you let me know what I have to change in css to make the gallery centered? I tried setting margin: 0 auto; and it did not work.

        Thank you

    • Are you able to fix this problem..?

      I modified the container gallery as follows…

      float: center;
      margin-left: 75px;

      I haven’t tried the responsive setting of my website yet, see if it will help you…

      Reply
  16. Hi im getting

    Uncaught TypeError: $(…).simpleLightbox is not a function
    at HTMLDocument. ((index):1166)
    at l (jquery-3.3.1.min.js:2)
    at c (jquery-3.3.1.min.js:2)

    Any idea why? I have /js/dist/ and /js/src/ from the github… none of the js files work even .jquery.min.js and .min.js and just .js… HELP!

    Reply
  17. Same problem here:
    Uncaught TypeError: $(…).simpleLightbox is not a function
    at HTMLDocument. ((index):1166)
    at l (jquery-3.3.1.min.js:2)
    at c (jquery-3.3.1.min.js:2)

    Reply
  18. Great gallery, neat and simple.
    If I can ask, is possible to set the opacity of the background when I open an image? In other words, I would like to hide all the background content when I see the slide.
    Thank you again

    Reply
  19. Hi Yogesh,
    I downloaded the source file and it’s running perfectly, however, I’m not getting the right result when I added more photographs. Right now it’s only showing the first 12, the new ones are missing in action, could you please tell me why it’s not displaying them?

    Thanks a lot and have a good day.
    Ed

    Reply
  20. I’m using Google Chrome browser and it’s working perfectly, I also resized all photographs to 300px width and auto height. I viewed the page source and all photos are processed.

    One more thing, is it possible to replace the column (4) by a global variable (CSS) for responsive web design, and can you show me how it’s done?

    Thanks for your help…

    Reply
  21. Hi Yogesh,
    I resized all the photos again using 300px width and now they’re all displaying properly.

    I tried initializing external variable in style.php to set the number of columns per media screen size, as below…

    then call it up…

    (if( $count%$column == 0)
    however, it cannot access that variable from style.php, hence, this error…

    Notice: Undefined variable: column in C:\xampp\htdocs\login.com\index.php on line 56

    Fatal error: Uncaught DivisionByZeroError: Modulo by zero in C:\xampp\htdocs\login.com\index.php:56 Stack trace: #0 {main} thrown in C:\xampp\htdocs\login.com\index.php on line 56

    Have you tried using external variable in php before?

    Thanks again, I really appreciate your help…

    Reply
  22. Below initialized in style.php but doesn’t print above, I took out

    header(‘Content-type: text/css; charset: UTF-8’);
    $column = 5;

    Reply
  23. Thanks so much for this awesome code – it’s exactly what I needed as a foundation, so clean and easy, great job! One thing I can’t seem to figure out is that it won’t show on an iphone (mobile Safari) – wondering how to handle that. My PHO skills are very good, but my CSS skills are not!

    Thanks again for the great code!

    Reply
  24. Regarding sorting, I managed to sort files by replacing the these lines on the code:

    // Read files
    – while (($file = readdir($dh)) !== false){
    – if($file != ” && $file != ‘.’ && $file != ‘..’){

    // Read files
    + $files = scandir($dir);
    + rsort($files);
    + foreach ($files as $file) {
    + if ($file != ‘.’ && $file != ‘..’) {

    Thanx for this great code Yogesh!

    Reply

Leave a Reply to Josh Cancel reply