Search code examples
phpimagegalleryusinggenerate

How do I populate Image gallery using PHP on html page, including image code/classes either side?


I am creating a webpage that has a photo gallery, which is a lightbox, that uses a lot of images - around 80-150 per page. The number of the images changes week by week, and I would like to have the website automatically populate the image gallery from the images in a subfolder, whilst including the code attached to the image to make it display correctly.

For example, this is what each images code will look like. And please note that i'll need the image located twice on each line.

<a data-fancybox="gallery" href="images/001.jpg"><img alt="" class="lazy" data-src="images/001.jpg" /></a>

I am attempting to use the below script, but it doesn't appear to be working.

<?php
   $dirname = "../images/";
$images = glob($dirname."*.jpg");

foreach($images as $image) {
    echo '<a data-fancybox="gallery" href="'.$image.'"><img alt="" 
class="lazy" data-src="'.$image.'"  /></a>';
}
     ?>

In this case for each line I have included the .$image. in two locations, inbetween the echo's but it doesn't seem to be working.

If you have any advice for me it will be greatly appreciated.


Solution

  • Your <img /> tag doesn't have the path set in the src attribute which is needed to render the image by the browser. It only has data-src attribute filled.

    Should be:

    <?php
    $dirname = "../images/";
    $images = glob($dirname."*.jpg");
    
    foreach($images as $image) {
        echo '<a data-fancybox="gallery" href="'.$image.'"><img alt="" 
    class="lazy" src="'.$image.'" data-src="' . $image . '"  /></a>';
    }
    ?>