How to Fetch All Images From a Directory Using PHP?

0 comments

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;
            }
        }
closedir($dh);
($images); 
}} 
?>

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

<?php 
$i=0;
foreach($images as $r)
{ $i++;?>
<li>
<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>
<span>
<a href="images/<?php echo $r;?>" rel="prettyPhoto" >

</a>
</span>
</div>
</li>
<?php
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

Loading...