Create an Image Gallery from Folder Using PHP

In this tutorial, we will look into how to create an Image gallery that read all the images in a specific folder and show them as thumbnails.
When the user clicks on one of the image thumbnails, it will pop up and reveal itself with a larger view.

Overview

To continue in this users will need to create the following files to be saved all in the same directory.

  • Index.php
  • A Folder Called “gallery” in the same directory

Index.php

This file consist of PHP, HTML and CSS codes that read all the image present in the gallery folder (file types which are specified in the code ($num_files = glob($folder_path . “*.{JPG,jpg,gif,png,bmp}”, GLOB_BRACE); ) )and show them using HTML anchor tag.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tutorial-21</title>
<style type="text/css">

body
{
background:#000;
}
img
{
width:auto;
box-shadow:0px 0px 20px #cecece;
-moz-transform: scale(0.7);
-moz-transition-duration: 0.6s;
-webkit-transition-duration: 0.6s;
-webkit-transform: scale(0.7);

-ms-transform: scale(0.7);
-ms-transition-duration: 0.6s;
}
img:hover
{
box-shadow: 20px 20px 20px #dcdcdc;
-moz-transform: scale(0.8);
-moz-transition-duration: 0.6s;
-webkit-transition-duration: 0.6s;
-webkit-transform: scale(0.8);

-ms-transform: scale(0.8);
-ms-transition-duration: 0.6s;

}
</style>
</head>
<body>
<?php
$folder_path = 'gallery/';

$num_files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE);

$folder = opendir($folder_path);

if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'gif' || $extension == 'bmp')
{
?>
<a href="<?php echo $file_path; ?>"><img src="<?php echo $file_path; ?>" height="250" /></a>
<?php
}
}
}
else
{
echo "No Images Found";
}
closedir($folder);
?>
</body>
</html>

The CSS codes between <style type=”text/CSS”>……………….</style> is used to add some design and style to the page. You can add additional styling according to the need.

Bonus

You can download Full source code here.
[button style=”btn-success btn-lg” icon=”glyphicon glyphicon-download-alt” align=”left” iconcolor=”#81d742″ type=”link” target=”true” title=”Button” link=”https://app.box.com/s/9yn6whc5qsjjuiyv4f4cip0woeuvnh2p” linkrel=””]
If you face any challenge during the process feel free to comment or direct a mail I would happy to help you.
If you find this post helpful don’t forget to share it with your friends and community.

 

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

Leave a Reply

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