Very Simple PHP Video Gallery (No Database, From Folder)

Welcome to a tutorial on how to create a simple responsive PHP video gallery. Once upon a time in the stone age of the Internet, we have to struggle with all kinds of funky 3rd party video plugins to even play a single video. Fast forward to today, things are really easy.

Creating a simple video gallery in PHP is as easy as:

  • Get a list of video files from the folder – $vids = glob("GALLERY/*.{webm,mp4,ogg}", GLOB_BRACE);
  • Output the HTML video tags – foreach ($vids as $v) { echo "<video controls src='". rawurlencode(basename($v)) ."'></video>"; }

Yep, let us build a video gallery based on that – Read on!

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

SIMPLE PHP VIDEO GALLERY

All right, let us now get into more details about the PHP video gallery.

 

TUTORIAL VIDEO

 

PART 1) VIDEO GALLERY PAGE

1a-gallery.php
<!-- (A) CLOSE FULLSCREEN VIDEO -->
<div id="vClose" onclick="vplay.toggle(false)">X</div>

<!-- (B) VIDEO GALLERY -->
<div class="gallery"><?php
  // (B1) GET ALL VIDEO FILES FROM THE GALLERY FOLDER
  $dir = __DIR__ . DIRECTORY_SEPARATOR . "gallery" . DIRECTORY_SEPARATOR;
  $vid = glob("$dir*.{webm,mp4,ogg}", GLOB_BRACE);
 
  // (B2) OUTPUT ALL VIDEOS
  if (count($vid) > 0) { foreach ($vid as $v) {
    printf("<video src='gallery/%s'></video>", rawurlencode(basename($v)));
  }}
?></div>

  1. <div id="vClose"> This “close” button will only show when a video is in fullscreen.
  2. As in the introduction – Get all video files in the gallery folder, and output them into <video> tags.

 

 

PART 2) CSS COSMETICS

1b-gallery.css
/* (A) GALLERY WRAPPER */
/* (A1) BIG SCREENS - 3 IMAGES PER ROW */
.gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 10px;
  max-width: 1200px;
  margin: 0 auto; /* horizontal center */
}
 
/* (A2) SMALL SCREENS - 2 IMAGES PER ROW */
@media screen and (max-width: 768px) {
  .gallery { grid-template-columns: repeat(2, 1fr); }
}
 
/* (B) GALLERY VIDEOS */
/* (B1) THUMBNAIL VIDEO */
.gallery video {
  width: 100%;
  height: 200px;
  object-fit: cover; /* fill | contain | cover | scale-down */
  cursor: pointer;
}
 
/* (B2) FULLSCREEN VIDEO */
.gallery video.full {
  position: fixed;
  top: 0; left: 0; z-index: 999;
  width: 100vw; height: 100vh;
  background: #000;
  object-fit: scale-down;
}

/* (C) EXIT FULLSCREEN */
#vClose {
  position: fixed; display: none;
  top: 0; right: 0; z-index: 9999;
  font-size: 20px; font-weight: 700;
  padding: 10px 15px;
  color: #fff;
  background: #741414;
  cursor: pointer;
}
#vClose.show { display: block; }

There’s quite a bit of CSS, but keep calm and let’s walk through the important mechanics:

  • (A1) display: grid and grid-template-columns: repeat(3, 1fr) pretty much does the “3 videos per row” layout magic.
  • (A2) On small screens, we change the layout to 2 videos per row.
  • (B1) width: 100% and height: 200px will automatically resize the videos, but the videos will be “out of proportion”. We use object-fit to change the resize behavior, change this and see for yourself; Pick one that you like.
  • (B2) On clicking a thumbnail video, we set it to fullscreen. Pretty much 100% viewport width and height, and a fixed position.
  • (C) The “close fullscreen video” button, place at the top right-hand corner.

 

 

PART 3) JAVASCRIPT

3-gallery.js
var vplay = {
  // (A) INIT - CLICK VIDEO TO GO FULL SCREEN
  init : () => { for (let v of document.querySelectorAll(".gallery video")) {
    v.onclick = () => {
      if (!v.classList.contains("full")) { vplay.toggle(v); }
    };
  }},
 
  // (B) TOGGLE FULLSCREEN
  toggle : e => {
    // (B1) TOGGLE CLOSE BUTTON
    document.getElementById("vClose").classList.toggle("show");
 
    // (B2) TOGGLE VIDEO
    let v = e===false ? document.querySelector(".gallery .full") : e ;
    v.classList.toggle("full");
    v.controls = e===false ? false : true ;
    if (e===false) { v.pause(); }
  }
};
window.onload = vplay.init;

A bit of Javascript to drive the “click to fullscreen video”.

  1. On window load, init() will attach “click to toggle fullscreen” on all gallery videos.
  2. To toggle the fullscreen video. Basically, add/remove the full CSS class on the selected video.

 

EXTRAS

That’s all for this project, and here is a small section on some extras and links that may be useful to you.

 

EXTRA) FILE NAME AS VIDEO CAPTION

3-gallery.js
// (B2) OUTPUT VIDEOS
if (count($vid) > 0) { foreach ($vid as $v) {
  $file = basename($v);
  $caption = substr($file, 0, strrpos($file, ".")); 
  printf("<div class='vWrap'>
    <video src='gallery/%s'></video>
    <div class='vCaption'>%s</div>
  </div>", rawurlencode($file), $caption);
}}

There is no database, but we can still use the file name as the caption.

 

 

EXTRA) SORTING THE VIDEOS

Sort by date – newest first
usort($vid, function ($file1, $file2) {
  return filemtime($file2) <=> filemtime($file1); 
});
Sort by date – oldest first
usort($vid, function ($file1, $file2) {
  return filemtime($file1) <=> filemtime($file2);
});
Sort by file name.
sort($vid); // ascending
rsort($vid); // descending

 

EXTRA) MULTIPLE CATEGORIES

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

Same old “get the list of files and output HTML”, just keep your video files in different folders.

 

EXTRA) READ ANOTHER FOLDER

$vid = array_merge(
  $vid, glob("ANOTHER-FOLDER*.{webm,mp4,ogg}", GLOB_BRACE)
);

This is an alternative to reading multiple folders, just use array_merge() to combine the results. But of course, this is only good as a “quick fix”, this is not good if you have a dozen folders.

 

VIDEO FORMAT SUPPORT & POSTER

  • Different browsers support different video formats, the safest format at the time of writing is H.264 MP4 – See the Wikipedia HTML5 Video link below for the full list.
  • Depending on the Internet connection and/or video format, some browsers may not even preload the video and show a thumbnail. You can set a poster image to show while the video is still loading – <video poster="IMAGE.JPG">.
  • Alternatively, you can “encourage” the browser to preload a fragment of the video by changing the preload behavior – <video preload="metadata">.

 

COMPATIBILITY CHECKS

This simple gallery will work on all modern browsers.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

34 thoughts on “Very Simple PHP Video Gallery (No Database, From Folder)”

  1. This is so awesome, and exactly what I was looking for in a simple video gallery.
    Thanks so much.

    However, I do have one question. I am using IFrames on my page, where the php would be within the IFrame.

    When doing this, clicking on the video does not expand it to full screen, and I’m wondering what changes to the javascript function would be needed to get it to work in an IFrame?

    1. Thanks. I’ll look at that link.
      Also, I should have said html frameset and not iframe. That’s my bad. 🙁

      The code I’m using is from 2007 and before the tag, where I have to manually code in every new video clip into the html; which is why I was finally getting around to looking at gallery options such as yours.

      The reason for the frames, is that I have a narrow, scrolling menu on the left-hand frame, which when an item was clicked, it would open up an html page in the right-hand frame, which was populated with the video clips corresponding to that menu item. Changing the html pages to your php code works perfectly at auto-generating the videos in the right-hand frame.

      I like the idea of having them play full screen, or even just full to the frame size, so I’ll keep looking at ways to get it to work. 🙂

  2. Hey man,

    thanks for the awesome script.

    Is there any way we can make the thumbnail work on iOS (Safari and Chrome) does not show the preview of the video!

    Many Thanks!

  3. Jorge Fernandez

    Great article, very simple and works perfectly.

    Quick question, do you have any idea on how I would go about implementing pagination for this example or the image gallery example? I have a lots of files I would like to view using this, but I’ve never used pagination without a DB, or would it be better to just create a DB with the contents of the folder?

    I really enjoy your posts, keep up the awesome work my friend!

    Thank you!

    1. Well, it’s still possible with some changes.

      1) Use PHP $videos = glob(...) as usual.
      2) Use it to generate a JS array instead.
      $all = count($videos);
      var jsvideos = [<?php foreach($videos as $i=>$v) { echo '"$k"'; if($i<$all) { echo ","; } } >];
      3) Create a JS function to generate the gallery instead.
      var pagenow = 0; var perpage = 10;
      var container = document.getElementById("vid-gallery");
      container.innerHTML = "";
      for (let i=pagenow*perpage; i<(pagenow+1)*perpage) { let vid = document.createElement("video"); vid.src=jsvideos[i]; container.appendChild(vid); }
      4) Lastly, create a dropdown pagination box somewhere that will fire the above function and change the page.

  4. Hi,
    This is great post and I was looking for something like this. And further..
    How we can set below.
    Title for each video
    Share option on each video, so users can quickly share on social media
    Thanks in advance..
    Debeve

    1. That is not “very simple”, but closer to a “full video gallery”. If you need all those features, I will highly suggest doing a search for other available packages… Trying to build all those on top of this one is going to be a pretty crazy process.

Leave a Comment

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