3 Steps Very Simple PHP Gallery (From Folder No Database)

Welcome to a quick tutorial on how to create a very simple PHP gallery. Tired of all those complicated gallery plugins on the Internet?

Creating a no-database PHP image gallery is as easy as getting a list of image files using glob() and outputting them in HTML.

  • $images = glob("PATH/GALLERY/*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE);
  • foreach ($images as $i) { echo "<img src='gallery/". basename($i) ."'>"; }

Yep, just like that in 1 minute. But how does this work exactly? Let us walk through a no gimmicks image gallery in this guide – Directly reads image files from a folder, no database required. Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Simple Gallery Useful Bits & Links
Tutorial Video The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

  • gallery.php – The simpler gallery without image caption.
  • caption-gallery.php – Alternate version with image caption.
If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

 

STEP 1) PHP & HTML

gallery.php
<!-- (A) CSS & JS -->
<link href="gallery.css" rel="stylesheet">
<script src="gallery.js"></script>
 
<div class="gallery"><?php
// (B) GET LIST OF IMAGE FILES FROM GALLERY FOLDER
$dir = __DIR__ . DIRECTORY_SEPARATOR . "gallery" . DIRECTORY_SEPARATOR;
$images = glob("$dir*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE);
 
// (C) OUTPUT IMAGES 
foreach ($images as $i) {
  printf("<img src='gallery/%s'/>", basename($i));
}
?></div>

Yep, that’s all to the gallery page. As in the introduction, all we are doing here is –

  • Get a list of image files from the gallery folder using glob().
  • Then throw them into the <div class="gallery"> gallery container.

 

 

STEP 2) THE CSS

gallery.css
/* (A) GALLERY CONTAINER */
/* (A1) ON BIG SCREENS */
.gallery {
  display: grid;
  grid-template-columns: repeat(3, auto); /* 3 IMAGES PER ROW */
  grid-gap: 10px;
  max-width: 1200px;
  margin: 0 auto; /* HORIZONTAL CENTER */
}
/* (A2) ON SMALL SCREENS */
@media screen and (max-width: 640px) {
  .gallery {
    grid-template-columns: repeat(2, auto); /* 2 IMAGES PER ROW */
  }
}
 
/* (B) THUMBNAILS */
.gallery img {
  width: 100%;
  height: 200px;
  /* FILL, CONTAIN, COVER, SCALE-DOWN : USE WHICHEVER YOU LIKE */
  object-fit: cover;
}
.gallery img:fullscreen { object-fit: contain; }
 
/* (X) DOES NOT MATTER */
body, html {
  padding: 0;
  margin: 0;
}

Of course, we are not so “barbaric” to just row out raw images without any cosmetics. So here is how we use a simple CSS grid to layout the images into a nice gallery, also add some responsive mobile-friendly magic. Please feel free to modify these to fit your own project.

 

 

STEP 3) JAVASCRIPT FULLSCREEN IMAGE

gallery.js
window.addEventListener("DOMContentLoaded", () => {
  // (A) GET ALL IMAGES
  var all = document.querySelectorAll(".gallery img");
 
  // (B) CLICK ON IMAGE TO TOGGLE FULLSCREEN
  if (all.length>0) { for (let img of all) {
    img.onclick = () => {
      // (B1) EXIT FULLSCREEN
      if (document.webkitFullscreenElement || document.fullscreenElement) {
        if (document.exitFullscreen) { document.exitFullscreen(); }
        else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); }
      }

      // (B2) ENGAGE FULLSCREEN
      else {
        if (img.requestFullscreen) { img.requestFullscreen(); }
        else if (img.webkitRequestFullscreen) { img.webkitRequestFullscreen(); }
      }
    });
  }}
});

Lastly, a small Javascript snippet to “click on an image to toggle fullscreen mode”.

 

 

EXTRA) FILENAME AS IMAGE CAPTION

caption-gallery.php
foreach ($images as $i) {
  $img = basename($i);
  $caption = substr($img, 0, strrpos($img, "."));
  printf("<figure><img src='gallery/%s'/><figcaption>%s</figcaption></figure>", $img, $caption);
}

Since there is no database, there is nowhere we can store the captions. But we can still use the file name as the caption of the images – This is just a small modification to the PHP to also output the <figcaption>.

 

EXTRA) SORTING THE IMAGES

Sort by date.
usort($images, function($file1, $file2) {
  // NEWEST FILE FIRST
  return filemtime($file2) <=> filemtime($file1); 
  // OLDEST FILE FIRST
  // return filemtime($file1) <=> filemtime($file2);
});
Sort by file name.
sort($images); // LOW TO HIGH
rsort($images); // HIGH TO LOW

 

EXTRA) MULTIPLE CATEGORIES

<h1>CATEGORY A</h1>
<div class="gallery"><?php
  $images = glob(FOLDER A);
  foreach ($images as $i) { printf("<img ... />"); }
?></div>
 
<h1>CATEGORY B</h1>
<div class="gallery"><?php
  $images = glob(FOLDER B);
  foreach ($images as $i) { printf("<img ... />"); }
?></div>

Just put your images into different category folders, and repeat the “get list of files and output HTML”.

 

 

EXTRA) READ ANOTHER FOLDER

$images = array_merge(
  $images, glob("ANOTHER-FOLDER*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE)
);

This is another alternative to read another folder, simply use array_merge() to combine the results. Of course, this is good as a “quick fix” only. Not recommended if you have a dozen folders.

 

EXTRA) INCLUDE VIDEOS

// (A) GET IMAGES & VIDEOS
$media = glob("$dir*.{jpg,jpeg,gif,png,bmp,webp,avi,mp4}", GLOB_BRACE);
 
// (B) OUTPUT HTML
foreach ($media as $i) {
  $parts = pathinfo($i);
  if ($parts["extension"]=="avi" || $parts["extension"]=="mp4") {
    printf("<video src='gallery/%s' controls></video>", basename($i));
  } else { printf("<img src='gallery/%s'/>", basename($i)); }
}

But the problem is – How to deal with video playback. Play while in the thumbnail size? Or engage in full-screen mode first? Check out the video gallery tutorial below if you want more.

 

USEFUL BITS & LINKS

That’s it for all the code. Here are some extras that may be useful to you.

 

COMPATIBILITY CHECKS

Full-screen mode is still not fully supported on iPhones at the time of writing… So much for calling themselves “advanced”. Use the Modernizr library to detect and load a fallback or alternative if you want.

 

USEFUL LINKS

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

Simple No Database Gallery With PHP (Click to Enlarge)

 

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope that it has helped you to create a better (and simpler) image gallery, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

54 thoughts on “3 Steps Very Simple PHP Gallery (From Folder No Database)”

  1. hi great tutorial, thanks, would it be possible to have all the images in one row with left and right scroll buttons, similar to a carousel?
    thanks very much !

  2. Great PHP Gallery, easy and simple. Thank you so much for the tutorial!. I have problems with PNG files with transparent background. The thumbnails created are all black. Is there a way to add background, for example in white? When i try to open the thumbnails in file explorer, it tells me that the files are corrupt….
    Thank you again!

      1. Yeah! That was great! I changed de CSS to avoid pixeling small images:
        #gallery img {
        box-sizing: border-box;
        width: 25%;
        max-height: 150px;
        padding: 5px;
        /* fill, contain, cover, scale-down : use whichever you like */
        object-fit: contain; <– changed from cover.
        cursor: pointer;
        }
        Now i'll try to make all directory recursive.
        Tank you so much!

  3. Is the gallery great, a query, how could it be modified so that the latest added photos are the first to be seen? Thank you.

      1. Hi, great tutorial for lightweight solution!
        I have a hard time applying this properly to your tutorial. How and where would you add this?
        Also is there a possibility to add left and right buttons to cycle through the images once you open them to the lightbox?
        Newbie asking. Thanks! 🙂

      2. Yes, of course, it is possible to add left/right on top of this one – But if you are having trouble understanding this “barebones gallery”, I will highly suggest you start with the basics and understand what is going on first… P.S. Read the entire tutorial, the answer is literally right above in the extras section.

  4. thank you for this solution.
    i could use some help with two issues:
    1) what is needed to be able to replace the “gallery” folder with /full/path/to/some/other/folder? i tried this and my gallery remained white
    2) when i click images that are too big for the screen, they do get opened full size and it is not possible to use scrollbar, middle click, etc. how to i tell php/js to just scale correctly?

    best
    benedikt

      1. Thanks W.S. Toh for your very nice gallery code, it helped me a lot.
        I had the same issue as benedikt and i made light changes that fully address the needs in responsive mode:
        I modified only 2 lines in the “file 2-box.css”:

        #lfront img {
        max-width: auto;
        max-height: 100vh; <=== this first line modified
        margin: 0 auto;
        display: block;
        }
        #lback {
        height: 100vh; <=== this second line modified
        background: #000;

        Best regards. johann

  5. Great Job!!!!
    its posible to add buttons under the image popup to share on Instagram, Facebook and tweeter???

  6. Super easy and simple. Thank you!

    One thing someone else may run into:

    My camera by default would make the file name and extension all in uppercase. So the script behaved like the gallery folder was empty until I changed all the photos from .JPG to .jpg

    1. Just add Uppercase JPG to the selection … faster

      $files = glob($dir . “*.{JPG,jpg,jpeg,gif,png}”, GLOB_BRACE);

Leave a Comment

Your email address will not be published.