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.

 

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.

 

QUICK NOTES

  • There are 2 different versions in the zip file.
    • gallery.php – The simpler gallery without image caption.
    • caption-gallery.php – Alternate version with image caption.

If you spot a bug, please feel free to comment below. I try to answer 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.

 

 

 

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.

 

 

3) JAVASCRIPT FULLSCREEN IMAGE

gallery.js
window.addEventListener("DOMContentLoaded", function(){
  // (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.addEventListener("click", function(){
      // EXIT FULLSCREEN
      if (document.webkitFullscreenElement || document.fullscreenElement) {
        if (document.exitFullscreen) { document.exitFullscreen(); }
        else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); }
      }

      // ENGAGE FULLSCREEN
      else {
        if (this.requestFullscreen) { this.requestFullscreen(); }
        else if (this.webkitRequestFullscreen) { this.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>.

 

 

USEFUL BITS & LINKS

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

 

FILE SORT

Need to sort the files by the file timestamp? Use the usort() method after getting the list of image files.

// $images = glob(...);
usort($images, function($file1, $file2) {
  // NEWEST FILE FIRST
  return filemtime($file2) <=> filemtime($file1); 
  // OLDEST FILE FIRST
  // return filemtime($file1) <=> filemtime($file2);
});

Or to sort in the alpha-numeric order:

sort($images); // LOW TO HIGH
rsort($images); // HIGH TO LOW

 

READING MULTIPLE FOLDERS

The glob() function simply returns an array of image files, so we can combine it with the use of array_merge() when required.

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

But of course, this is good only as a “quick fix”. Not recommended if you have a dozen folders.

 

MULTIPLE CATEGORIES

If you have multiple folders, each for a different category, simply repeat the “get an array of image files, output in HTML”.

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

 

 

SUPPORTING VIDEOS

It is possible to do so… But it does require quite a bit of extra work. First, simply add video extensions into glob().

$images = glob($dir . "*.{jpg,jpeg,gif,png,bmp,webp,avi,mp4}", GLOB_BRACE);

Then, modify the PHP to output both HTML image and video.

foreach ($images 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));
  }
}

Finally, 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 LINKS

 

TUTORIAL VIDEO

 

THE 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!

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

  1. Excellent tutorial & example code – thank you. Using the unmodified files from your .zip, in Safari on MacBookPro, the sunflower image does not appear. And clicking on any image does not make it full screen (fails also on iPad/iPhone) but everything seems to work fine on Windows 10 with Edge.

    1. Fullscreen – Fixed. Just Apple being Apple for not adopting the standard requestFullscreen().

      WEBP – Cannot be fixed. Just Apple being Apple for not adopting the WEBP image format. Ignore and use JPEG images in your own project.

      1. Hi, I have still problem with Full Screen Lightbox photos on Safari on iPhone , can you tell me and help how to fix that ?? Evertyhing looking fine in code.

  2. Matthieu Dalstein

    Thanks a lot for this very interesting page.
    It seems that the download link is broken. Could you please update it ?

    1. Rename “index.html” to “index.php”.

      As simple as this may be, a small degree of technical knowledge is still required. If you are standing at “zero” – I will highly recommend hiring a freelancer to help.

  3. Hello! Really great tutorial, helped me a lot with understanding how to implement html, php and js together.
    I have one question, is it possible to add pages? The reason would be that having a lot of images would slow down the browser and also use up a lot of ram. I know this isnt the right way of doing something like this but I want to achieve as much as I can without needing a database.
    So would paging, or any other way of displaying large amounts of images with this method be possible?

    1. Not entirely impossible, just needs more calculations.

      // (A) GET IMAGES
      $dir = "d:/temp/";
      $images = glob($dir . "*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE);
      
      // (B) PAGINATION CALCULATE
      $total = count($images);
      $perpage = 10;
      $pages = ceil($total / $perpage);
      $current = isset($_GET['pg']) ? $_GET['pg'] : 1 ;
      if ($current > $pages) { $current = $pages; }
      
      // (C) OUTPUT
      $start = ($current-1) * $perpage;
      $end = $start + $perpage;
      if ($end > $total) { $end = $total; }
      for ($i=$start; $i<$end; $i++) { echo $images[$i]; }
      
  4. HI,
    This is a great tutorial. Works wonderfully for my image gallery. But can you help me add a close button and left/right arrows once the image is opened in full size in the lightbox?
    Thanks

  5. This tutorial is amazing! Thank you for this.

    I’ve been playing with the code and I’m wondering how I could have multiple instances of this PHP code on the same page showing galleries from different folders as separate elements. Is that possible?

    1. Jean-Marie Larchevêque

      If you find that { object-fit: cover; } changes the aspect ratio of narrow portrait photos (as I found it did for me, though I understand it’s not supposed to), you can use { object-fit: contain; } instead.

  6. Great and detailed tutorial! Very impressed with how fast you reply to questions! 🙂

    I have two questions that I cannot find in the answer for in the guide or in the previous comments.
    1. How could I create an area with text below or above the lightbox image? For example a button to open image in new tab, or show the image title/name?
    2. I understand I can upload from multiple folders. I would love to have a sorting option by image tags. For example sort by car-images or sort by fruit-images. Is there a way to set a tag to each image?

    Thank you very much in advance!

    1. Just add a <div> into the lightbox? <div id="lfront"><div id="lbcaption"></div></div>.
      But given all your requirements – There is no database to store captions, tags, titles, nor are there additional data that can be used for “custom sorting”. I will highly recommend you look for a “full-featured gallery”, or building on top of this is going to be a long painful process…

    1. glob(FOLDER . "*.{FILE EXTENSION}", GLOB_BRACE) simply returns an array of files, so –

      * Just add the video files (.mp4, .webm, .avi) to the list of file extensions.
      * Just use $images = array_merge($images, glob(FOLDER 2, ...)) for more folders.
      * In the for loop, check for video files (hint: file_info() function), and generate <video> tags instead of image.
      * Update the CSS and Javascript to also support video.

Leave a Comment

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