Generate a photo gallery from an image directory in PHP.

An image gallery can show a large number of photos on an online site efficiently. The gallery lets the user view all images that occur all over the site from one place.

There are three ways you can create an image gallery. The first one manually adds all images to your page and makes an image gallery. The second way is to store the image file names into the database. And the last one is from a directory. In this guide, you will see how you can create a dynamic image gallery from a directory in PHP.



  • Isotope – To make our image gallery Pinterest type resposive masonry grid. Because Images may be of different sizes.
  • Lightbox2 – This is a simple lightbox plugin. We need to also add this features to our image gallery.
  • Bootstrap 4 (Optional) – This is optional. If you want to use Bootstrap to your site, you can use it.

Include CSS and JS:

Here we are using two plugins i.e. Isotope and Lightbox2. You can either download and use the files directly on your server or use the CDN version. Lightbox2 needs some image files. That’s why I am not going to use its CDN version. For Isotope, we will use its CDN version. First, check the directory structure.

image gallery structure


<!-- Bootstrap CSS (Optional)-->
<link rel="stylesheet" href="">

<!-- Lightbox CSS (See the above folder structure)-->
<link rel="stylesheet" href="assets/css/lightbox.min.css"/>


We are going to use our all scripting files before the end of the </body> tag.

<!-- Jquery-->
<script src=""></script>

<!-- Bootstrap JS (Optional)-->
<script src=""></script>

<!-- Lightbox JS (See the above folder structure)-->
<script src="assets/js/lightbox.min.js"></script>

<!-- isotope JS-->
<script src=""></script>

Basic HTML Structure

<div class="gallery-list">
	<div class="gallery-item">
		<a href="images/1.jpeg" data-lightbox="gallery">
			<img src="images/thumb/1.jpeg"/>

This is a basic HTML structure. With PHP we will automatically show all the images in a folder in this structure.

  • .gallery-list will wrap the all image items.
  • .gallery-item denotes each image item from folder.
  • Suppose, images folder has a file named 1.jpeg that is high resolution picture <a href="images/1.jpeg" data-lightbox="gallery">
  • The thumb folder, inside the images will store the same image, but in low resolution <img src="images/thumb/1.jpeg"/> for fast loading.
  • In data-lightbox="gallery", you can use what ever you want instead of gallery.
  • Basically it will group all the pictures. And when there is a slideshow after clicking on an image, it will only show images whose group id is gallery.

Apply CSS

.gallery-list {
	margin: auto;
	left: 7px;

.gallery-item {
	width: 20%;
	margin-bottom: 15px;
	position: relative;
	overflow: hidden;
	cursor: pointer;

.gallery-item img {
	width: 100%;
	height: auto;
	vertical-align: top;
	webkit-filter: grayscale(50%);
	-moz-filter: grayscale(50%);
	-o-filter: grayscale(50%);
	-ms-filter: grayscale(50%);
	filter: grayscale(50%);
	-webkit-transition: all 0.5s ease-in-out;
	-moz-transition: all 0.5s ease-in-out;
	-o-transition: all 0.5s ease-in-out;
	transition: all 0.5s ease-in-out;

.gallery-item:hover img {
	-webkit-filter: grayscale(0%);
	-moz-filter: grayscale(0%);
	-o-filter: grayscale(0%);
	-ms-filter: grayscale(0%);
	filter: grayscale(0%);
	-webkit-transform: scale(1.2) rotate(-3deg);
	-moz-transform: scale(1.2) rotate(-3deg);
	-o-transform: scale(1.2) rotate(-3deg);
	-ms-transform: scale(1.2) rotate(-3deg);
	transform: scale(1.2) rotate(-3deg);

To make our image gallery more attractive, I have added some transitions and styles.

  • By using filter: grayscale(50%);, initially, we will make our image 50% gray.
  • In .gallery-item:hover img, it will automatically return to the origional state by making grayscale to 0 filter: grayscale(0%);.
  • We also want to rotate and scale our image when user hover over the image item by using transform: scale(1.2) rotate(-3deg);

Generate a photo gallery from an images directory in PHP

This is not possible for us to add all images manually from a directory. That’s why we will use PHP to get all the images.

<div class="gallery-list">
	//get current directory
	$working_dir = getcwd();
	//get image directory
	$img_dir = $working_dir . "/images/";
	//change current directory to image directory
	//using glob() function get images 
	$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}", GLOB_BRACE );
	//again change the directory to working directory
	//iterate over image files
	foreach ($files as $file) {
		<div class="gallery-item">
			<a href="<?php echo "images/" . $file ?>" data-lightbox="gallery">
				<img src="<?php echo "images/thumb/" . $file ?>"/>
	<?php }
  • First store the current directory in a variable using getcwd().
  • To get the image directory, we need to string concatination here i.e. $working_dir . “/images/”; and store it to $img_dir variable.
  • Now change the current directory location to image directory chdir($img_dir);.
  • To get the all images from a directory, we are going to use PHP glob() function.
  • Using the GLOB_BRACE flag, we can search for files with extensions jpg, gif, png like this glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}", GLOB_BRACE ); and store it into a variable called $files.
  • You can see we have written the extension into the brace “{}” i.e. jpg and JPG. This is because, GLOB_BRACE flag is case sensitive.
  • Again change the directory to root directory chdir($working_dir);.
  • We have changed our curret directory to images directory because if you simply pass glob("images"), it will return image filename with directory name i.e. “images/1.jpeg”. To get rid of that, we have changed our directory to get only image file name.
  • Now iterate over image files and generate HTML structure dynamically for our gallery.

Make image gallery like pinterest

We have done the main work. Now let’s see how we can make this image gallery look like a responsive masonry grid just like Pinterest.

If you don’t know what a masonry grid is, then you can check our demo. Basically, it does not have a fixed height. This is because we have different sizes of images. It helps to reduce any unnecessary gaps between the images.


			// debouncing function from John Hann
			var debounce = function(func, threshold, execAsap) {
				var timeout;
				return function debounced () {
					var obj = this, args = arguments;
					function delayed () {
						if (!execAsap)
							func.apply(obj, args);
							timeout = null;
					if (timeout)
					else if (execAsap)
					func.apply(obj, args);
					timeout = setTimeout(delayed, threshold || 50);
			// smartresize
			jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

		var colWidth = function () {
			var w = $container.width(),
				columnNum = 1,
				columnWidth = 0;
			if (w > 1200) {
				columnNum  = 3;
			} else if (w > 900) {
				columnNum  = 3;
			} else if (w > 600) {
				columnNum  = 3;
			} else if (w > 400) {
				columnNum  = 2;
			}else if (w > 300) {
				columnNum  = 1;
			columnWidth = Math.floor(w/columnNum);
			columnWidth = columnWidth - 10;
			// Item width
			$container.find('.gallery-item').each(function() {
				var $item = $(this);
				var multiplier_w = $item.attr('class').match(/item-w(\d)/);
				var width = multiplier_w ? columnWidth*multiplier_w[1]-4 : columnWidth-4;
				// Update item width
					width: width
			return columnWidth;

		var $container = $('.gallery-list');
			resizable: false,
			itemSelector: '.gallery-item',
			percentPosition: true,
			masonry: {
				columnWidth: colWidth(),
				gutter: 10,


You can use any type of image. Make sure you put the same image with lower resolution inside the thumb directory. Depending on your directory structure, you can change the directory names per your requirement. That’s all for today’s tutorial. If you have any questions please comments below.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

5 thoughts on “Generate a photo gallery from an image directory in PHP.”

  1. Hy,
    Good tutorial, but when loading images, many of them appear cutted, till refreshing the page.

    Is there any solution.


  2. Hello Asish,
    I am using the code from this article in a new website and encounter the same problem as mentioned by Roberto.
    After reading your comment to him I also loaded the “imagesloaded” script. But I can’t figure out where to put the code that you mention in your comment. I looked at all the codepen’s on the desandro website but nothing works in my situation. Can you be more specific about the code and were to put it?


Leave a Comment