How to Fetch All Images From a Directory Using PHP?


With using PHP you can make a dynamic picture gallery page where you can fetch all images stored in a folder.
Create a PHP file, e.g gallery.php
Add the below code in your file.

<?php $dir = "images/";
// Give the path of folder where all images are saved
if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        $images = array();

        while (($file = readdir($dh)) !== false) {
            if (!is_dir($dir.$file)) {
                $images[] = $file;

Now Add this loop to your div where you want to fetch images..

foreach($images as $r)
{ $i++;?>
<div class="gallery_item">
<a href="images/<?php echo $r;?>" class="lightbox" rel="gallery">
<img src="images/<?php echo $r;?>" width="284" height="127" alt="" />
<a href="images/<?php echo $r;?>" rel="prettyPhoto" >

if($i%3==0) // sets the limit of pictures in a row(e.g i%3 = 3 pictures in a row)
{ //echo "<br>";

Live Demo
Download Demo

Categories: Php, Technologies

Leave A Comment