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
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
<!-- (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>
<div id="vClose">
This “close” button will only show when a video is in fullscreen.- As in the introduction – Get all video files in the
gallery
folder, and output them into<video>
tags.
PART 2) CSS COSMETICS
/* (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
andgrid-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%
andheight: 200px
will automatically resize the videos, but the videos will be “out of proportion”. We useobject-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
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”.
- On window load,
init()
will attach “click to toggle fullscreen” on all gallery videos. - 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
// (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
usort($vid, function ($file1, $file2) {
return filemtime($file2) <=> filemtime($file1);
});
usort($vid, function ($file1, $file2) {
return filemtime($file1) <=> filemtime($file2);
});
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
- Arrow Function – CanIUse
- CSS Grid Layout – CanIUse
This simple gallery will work on all modern browsers.
LINKS & REFERENCES
- HTML5 Video – Wikipedia
- HTML Video Tag – MDN
- CSS Grid – MDN
- Fullscreen API – MDN
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!
I posted a question a few minutes ago and I’m not seeing it to reply to it, but I found the answer. I was trying to get the URL in the address bar updated when a video was clicked on and I did so by adding history.pushState(null,’test’,v.scr); to the var vplay function in 1c-gallery.js, as below. history.pushState, however, isn’t having the back button to work as it should so I’m looking further into that.
v.onclick = () => {
if (!v.classList.contains("full")) {
vplay.toggle(v);
history.pushState(null, 'test', v.src);
}
That
pushState
syntax is wrong, and you need more.1) Add unique ID to every video –
<video id="vidN">
2) Modify JS on click –
2.1) Update URL params
let url = new URL(window.location); url.searchParams.set("id", N);
2.2) Push state
history.pushState({id:N}, "", "gallery.php");
3) On window load and popstate, check for
?id=N
and click the video accordingly –let id = new URL(document.location).searchParams.get("id"); if (id!==null) { document.getElementById("vid"+id).click(); }
https://developer.mozilla.org/en-US/docs/Web/API/History/pushState
https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event
Good luck with your project.
This is a great script, and I managed to get it working, and even sorting with newest uoloads first.
Some of my videos are filmed with the camera in vertical orientation, but since the camera doesn’t know this, they are shown in horizontal orientation.
Is it possible to rotate these videos 90 deg when shown?
I can indetify the vertical videos by som characters in the filenames like this:
if (fnmatch(“*_Vert*”, $file))
but I have not been able to figure out if rotation is possible at all.
You can try to apply CSS rotate on all videos with
_vert
– https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotateBut otherwise, I think the “proper way” is to use a video editor to rotate the videos.
Thank you, that seems to work, but I have of couse some things to change to make it look right. But you pointed me in the right direction 🙂
You are right, that a video editor would be better, but the files are uploaded directly from the camera via FTP.
Hello, many thanks for sharing this excellent code! I have 1 question that I hope you can help with. How can I make it display the file name underneath each video?
Tutorial updated. See above.
Hi, thank you for this. I was hoping it would also grab videos from subfolders. so gallery/1/2/3/4 etc. Can you show me how to do that?
This is what I tried: $dir = __DIR__ . DIRECTORY_SEPARATOR . “{gallery/,gallery/**/,gallery/**/**/,gallery/**/**/**,gallery/**/**/**/**}” . DIRECTORY_SEPARATOR;
GLOB will not read subfolders, the only way is to create a recursive function. See the recursive example here – https://code-boxx.com/list-files-folders-php/
So Simple & Effective. Suits my purpose to a tee.
On thing I tried to change was to make the controls visible by default on the thumb-nails.
Can’t figure how to do that and it’s beyond the scope of my skills.
I see I can right click on them one by one & show controls, then have multiple files playing in thumbnail view. Even better when viewing Sky-Cam time-lapse.
Can you point me in the direction of what I need to change to do the above.
Thanks.
<video controls>
I don’t get it. Could have just done a Google search for “HTML video show controls”, and the answer is right there in 1 minute flat???