Are you faced with the task of organizing a large collection of image files into a visually appealing PHP photo gallery? There are the following solutions that you can use:
Solution 1:
One approach to creating a photo gallery is to manually add each image file to your web page individually. However, this method proves to be time-consuming and cumbersome, as it requires constant monitoring for any future updates to the image links.
Solution 2:
Another option involves storing the image names in a Database table and retrieving them when needed. This solution offers more efficiency and flexibility compared to the previous one.
Solution 3:
However, the most optimal solution involves reading all the files from your designated directory and generating an automated photo gallery. This approach eliminates the need for manual intervention and ensures that any changes or additions to the image directory are automatically reflected in the gallery.
In this post, I will focus on demonstrating the implementation of the third solution, utilizing the power of PHP. By following this guide, you will be able to create a dynamic and seamless photo gallery effortlessly.
So, without further ado, let’s dive into the exciting world of PHP photo galleries and discover how you can transform your image directory into an engaging visual experience!
Table of Content
- Download and Include simplelightbox library
- HTML and PHP: Create Photo Gallery layout
- CSS
- jQuery: Gallery Integration with SimpleLightbox
- Demo: See the PHP Photo Gallery in Action
- Conclusion
1. Download and Include simplelightbox library
- I am using
simplelightbox
jQuery library for making the gallery that you can download from here. - Include
simplelightbox.min.css
andsimple-lightbox.jquery.min.js
.
<link href='simplelightbox-master/dist/simplelightbox.min.css' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script type="text/javascript" src="simplelightbox-master/dist/simple-lightbox.jquery.min.js"></script>
2. HTML and PHP: Create Photo Gallery layout
Reading files from a directory with PHP.
- I am reading files from
images
the directory which also has sub-directorythumbnail
. - The directory and file structure looks like this –
Specified valid image extensions in the $image_extensions
Array variable and target directory in $dir
.
Read all files from the directory and set thumbnail and image path.
If it is a valid image and not a directory then use the path in the image source.
I only use $count
variable to show 4
images in a row.
<div class='container'> <div class="gallery"> <?php // Image extensions $image_extensions = array("png","jpg","jpeg","gif"); // Target directory $dir = 'images/'; if (is_dir($dir)){ if ($dh = opendir($dir)){ $count = 1; // Read files while (($file = readdir($dh)) !== false){ if($file != '' && $file != '.' && $file != '..'){ // Thumbnail image path $thumbnail_path = "images/thumbnail/".$file; // Image path $image_path = "images/".$file; $thumbnail_ext = pathinfo($thumbnail_path, PATHINFO_EXTENSION); $image_ext = pathinfo($image_path, PATHINFO_EXTENSION); // Check its not folder and it is image file if(!is_dir($image_path) && in_array($thumbnail_ext,$image_extensions) && in_array($image_ext,$image_extensions)){ ?> <!-- Image --> <a href="<?php echo $image_path; ?>"> <img src="<?php echo $thumbnail_path; ?>" alt="" title=""/> </a> <!-- --- --> <?php // Break if( $count%4 == 0){ ?> <div class="clear"></div> <?php } $count++; } } } closedir($dh); } } ?> </div> </div>
3. CSS
.container .gallery a img { float: left; width: 20%; height: auto; border: 2px solid #fff; -webkit-transition: -webkit-transform .15s ease; -moz-transition: -moz-transform .15s ease; -o-transition: -o-transform .15s ease; -ms-transition: -ms-transform .15s ease; transition: transform .15s ease; position: relative; } .container .gallery a:hover img { -webkit-transform: scale(1.05); -moz-transform: scale(1.05); -o-transform: scale(1.05); -ms-transform: scale(1.05); transform: scale(1.05); z-index: 5; } .clear { clear: both; float: none; width: 100%; }
4. jQuery: Gallery Integration with SimpleLightbox
Initialize simpleLightbox by calling simpleLightbox()
method on <a>
of gallery
class.
<!-- Script --> <script type='text/javascript'> $(document).ready(function(){ // Intialize gallery var gallery = $('.gallery a').simpleLightbox(); }); </script>
5. Demo: See the PHP Photo Gallery in Action
6. Conclusion
Creating a PHP photo gallery from an image directory offers a practical and efficient way to organize and display your image collection. Simply specify the folder location where your images are stored, and the PHP script will handle the rest, automatically skipping any non-image files it encounters.
Additionally, you have the flexibility to customize the gallery layout by utilizing other jQuery libraries.
With this knowledge, you can easily create a captivating and dynamic photo gallery using PHP, showcasing your images in an appealing manner to your audience.
If you found this tutorial helpful then don't forget to share.
Very nice script. Good article.
Thanks for reading!
Would be awesome if you could read the photo description from a text file. Would be good for SEO and you could add the description to the photo viewer.
Thanks for the TUT, i put it on my CV site. http://joshpetersen.me/pics
I modified the CSS to fit all images in the frame so nice and tidy.
object-fit: cover;
height: 10vw;
Hi,
could you show us how to dynamically add new photos to the gallery? I got a Photobox and a want to use this gallery on my webserver. If new photos are in the images folder i want to see them in the gallery too.
Best
Jens
Hi Jens,
I will try to publish a tutorial on this in next few days. Subscribe to the blog to get notified.
Did you published a tutorial for the automatic update?
I haven’t found it in your Blog.
Are there any news to this topic? It’s a really nice feature I’m already waiting for.
Can the gallery elements be updated automatically and being added with a smooth animation?
Dear Sir,
I found your gallery maker on the web.
I like it very much but there are a few things I seem not be able to control.
1. some pictures are not displayed in the correct orientation.
2. I do not understand the sorting. The pictures are not displayed in the order of the directory. To me it is like it is a random sort!
Maybe you can give me an indication how I can control the orientation and the sorting.
Greetings, Ad van Rossum
1. To fix this you can set the height of images.
2. For example, if you want to sort according to image name then use Array. Create an associative array and initialize it with thumbnail path and image path while reading files. You can get image name from the image path by extracting it.
e.g. $images_arr[‘imagename 1’]= array(‘thumbnail’=>$thumbanil_path,’image’=>$image_path);
Now sort the array by key ( image name ) using arsort() and loop on it to create images.
I hope helps.
Can you please post the code for this… I just do not have the PHP skills to do it.
I tried everything possible but I don’t understand it very well. Can you write this part of the code to sort by file name? Thnx
Hi Tom,
I will email you an example.
Can you please post the code / example of this – Image Sort
Dear sir,
1. set the height of image???
Where in the script?
Example please.
gr.
Set max and min height (style=’max-height: 200px;min-height: 200px;’) on tag inside the loop while reading files from the directory.
Do you mean somethin like this”?
<a href="”
<img style="max-height:40px;max-width:80px;height:auto;width:auto"
src="” alt=”” title=””/>
This had no effect on orientation only made thumbs smaller!!
You didnt include an index.html in your zip file?
how do I start the website.
I click index.php and it opens a text editor?
I’m on a MAC.
You need to run it with localhost on your system.
Hey Chad,
To see it in action you need to install PHP on your machine. I have installed apache2.4 and php (it took me hours to set it up). Using localhost setup i can test any php code and MySql database(You need to install mysql also for database, no need to install if you are not dealing with databases).
When it comes to website hosting they (most of service providers) already have these installed. So if you own a website than you can simply upload it to filemanager/public_html and you are good to go. No need to install and setup anything.
great article! How could i show the file name of the images underneath and add a way to click and download the image?
Hi Max,
The plugin I used in the example not allows what you are asking. You can either use any other plugin or customize the plugin.
Hi,
Downloaded all codes however not getting desired result. Please have a look of “https://sarojsymphonysociety.co.in/gallery.php” and suggest the update.
You need to reduce the size of the images or fix the width and height of images.
A very nice and handy little program to use.
Thanks.
actually i want image gallery like this , but want to download a file related to it. for example I will show a chair model image loaded automatically and when clicked it should download a zip file which has the 3dmodels and related to it can it be done with this script
how to sort files according to date
Hey,
Thanks for the script. Very useful. Just a few (minor) comments/suggestions (although I am not sure you keep this as a continuous development?):
– in your PHP list of accepted file-types, it would be useful to add the same ones in uppercase (many cameras have all filenames in uppercase by default …);
– to have no sorting is a bit tedious. I have seen your previous comment, which allow for many sorting options, but you also could use Scandir. However, for somebody who is not a PHP programmer it is a bit difficult to modify the script. A workaround is to upload the files one by one, instead of as a batch. In my case, my server default is that they are sorted by time of upload (so PHP takes that order).
All the best,
P.
Thanks, Peter for your feedback. I will try to update the tutorial soon.
hello Peter,
How you will use scandir in the code?
I tried your workaround but it’s not working for me (time of upload on my server)
tx in advance
william
Hey Yogesh,
I’m struggling a bit to have it work mainly because I not a php developer or even a html developer 🙂
I just try to add this script in my personal website http://www.oldspeed.net
Do you mind to send me the source file for https://makitweb.com/demo/photo_gallery/ at william@oldspeed.net?
Tx in advance
william
Hi William,
Download link is already available in the tutorial from where you can download the full source code.
and now i see the big download purple button…
Tx for your answer, I’m downloading it right now
I’ll give you credits in the code
I hope it’s ok to ask questions?
Everything is working well but when I click on a picture, i don’t have the effect as in your demo where the picture is showed over the gallery and there is 2 arrows and a X to close the picture
In my case, it open the picture on a black background and there is nothing to do from there (no arrows or X)
I’m missing something?
Umm… I have a problem with implementing it.
Not sure if I am putting the code in the wrong place or what, but while the script seems to work fine, it doesn’t upload any image and just leaves blank html image spot.
lightbox included – check
folder structure – check
gallery div with php placed in the body of html – probably wrong?
css inside css file – check
jquary script initialization – behind php script?
P.S. Ok, I got it working, Didn’t had PHP properly designated
Hi, I really love this photo gallery! Thanks for sharing!
Could it be that the closing action of the gallery is not supported by all browsers and/or browser versions? On one macbook I can use the close button, on my other I can’t, on mobile I can. Do you have any suggestions?
Still useful, man. Thank you. Simple, elegant way to display all of the images in a directory.
You’re welcome.
Hi Yogesh,
I’ve downloaded your example and have some remarks and questions :
as I launch index.php on local server the thumbnails are not displayed, only empty squares ???
but as I click on one, all run well, I see the big picture and the gallery runs …
I’ve put small pictures in /thumbnail/ dir … nothing appears
– why are the thumbnails unvisible ?
– does this php create the thumbnails ?? I’ve tried without any file in /thumbnail/ dir , same result !
– how can I block downloading capabilities by right-click ?
and … a great Thank You for your article
cheers
Christian
Hi Christian,
I have downloaded and run the tutorial code it is working. Check the folder has read permission or not. You can disable the right click on the image using jQuery. You can view this tutorial.
Yep Yogesh, you’re right, bad permission for the folder, run like a charm
Thanks !!!
Hi, this is a nice script, but not much use for many images without sorting by name, is there a chance you could add this please?, thank you
Very useful thanks! quick questions:
1) how to best generate thumbnails for 100 pictures?
2) any way to do it programatically?
Thanks!
Nice
I ve tried your PHP solultion, it works very nicelly for me, thanks. I higly recommend putting after last image. It helped me properly style gallery.
How do I center the gallery inside the browser? The gallery shows up left aligned always.
Hi Steve,
Have you tried adding width to the gallery and set margin: 0 auto;?
I noticed the gallery section in the style.css file already has margin: 0 auto in your source code. I also tried adding margin: 0 auto to all sections in style.css and the style sheets in the lightbox folders and was not able to center the gallery.
Any help would be greatly appreciated and I’m sure others would like to do this as well 🙂
Hi Steve,
Do you have a live link so I can view it?
Hi I don’t have a live link since i am running test on local apache server. Could you let me know what I have to change in css to make the gallery centered? I tried setting margin: 0 auto; and it did not work.
Thank you
Hi Steve,
Add the width and margin in <div class=”gallery”> like –
Are you able to fix this problem..?
I modified the container gallery as follows…
float: center;
margin-left: 75px;
I haven’t tried the responsive setting of my website yet, see if it will help you…
Hi im getting
Uncaught TypeError: $(…).simpleLightbox is not a function
at HTMLDocument. ((index):1166)
at l (jquery-3.3.1.min.js:2)
at c (jquery-3.3.1.min.js:2)
Any idea why? I have /js/dist/ and /js/src/ from the github… none of the js files work even .jquery.min.js and .min.js and just .js… HELP!
Honestly, I just downloaded the file versions from your demo, and I am now getting the pictures popping up at the end of my document page. Help
the same problem I had at the start. Easy, replace and turn off the old version of jquery with the latest version
Same problem here:
Uncaught TypeError: $(…).simpleLightbox is not a function
at HTMLDocument. ((index):1166)
at l (jquery-3.3.1.min.js:2)
at c (jquery-3.3.1.min.js:2)
Great gallery, neat and simple.
If I can ask, is possible to set the opacity of the background when I open an image? In other words, I would like to hide all the background content when I see the slide.
Thank you again
Hi Yogesh,
I downloaded the source file and it’s running perfectly, however, I’m not getting the right result when I added more photographs. Right now it’s only showing the first 12, the new ones are missing in action, could you please tell me why it’s not displaying them?
Thanks a lot and have a good day.
Ed
Have you checked the browser console? Is any error displaying?
I’m using Google Chrome browser and it’s working perfectly, I also resized all photographs to 300px width and auto height. I viewed the page source and all photos are processed.
One more thing, is it possible to replace the column (4) by a global variable (CSS) for responsive web design, and can you show me how it’s done?
Thanks for your help…
Hi Yogesh,
I resized all the photos again using 300px width and now they’re all displaying properly.
I tried initializing external variable in style.php to set the number of columns per media screen size, as below…
then call it up…
(if( $count%$column == 0)
however, it cannot access that variable from style.php, hence, this error…
Notice: Undefined variable: column in C:\xampp\htdocs\login.com\index.php on line 56
Fatal error: Uncaught DivisionByZeroError: Modulo by zero in C:\xampp\htdocs\login.com\index.php:56 Stack trace: #0 {main} thrown in C:\xampp\htdocs\login.com\index.php on line 56
Have you tried using external variable in php before?
Thanks again, I really appreciate your help…
Below initialized in style.php but doesn’t print above, I took out
header(‘Content-type: text/css; charset: UTF-8’);
$column = 5;
Thanks so much for this awesome code – it’s exactly what I needed as a foundation, so clean and easy, great job! One thing I can’t seem to figure out is that it won’t show on an iphone (mobile Safari) – wondering how to handle that. My PHO skills are very good, but my CSS skills are not!
Thanks again for the great code!
Regarding sorting, I managed to sort files by replacing the these lines on the code:
// Read files
– while (($file = readdir($dh)) !== false){
– if($file != ” && $file != ‘.’ && $file != ‘..’){
// Read files
+ $files = scandir($dir);
+ rsort($files);
+ foreach ($files as $file) {
+ if ($file != ‘.’ && $file != ‘..’) {
Thanx for this great code Yogesh!