0

So I am using this bit of PHP to display all the images in a particular directory:

<?php
  $dirname = "cards/";
  $images = glob($dirname."*.png");
  foreach($images as $image) {
  echo '<img src="'.$image.'" />';
  }
?>

It works fine to load my images. But I am wondering how I can have it echo the html to not only load the image, but display the file name as alt and title attributes. I tried using the following but it loads up the dir name as well as the file name. Trying to just get the file name.

echo '<img src="'.$image.'" alt="'.$image.'" title="'.$image.'" />';

In addition, I want to display only five images per row, is there a way of formatting that with automatically generated images?

UPDATE: In regards to displaying five images at a time, I don't want a slider or pagination. I want all images in the dir loaded, but with a line break after every 5 images.

Thanks in advance!

  • Do you understand what the `alt` and `title` properties are for? Right now the code seems to imply you're just going to repeat the file name. See: http://stackoverflow.com/questions/13146115/about-the-title-alt-attributes – Halcyon Aug 20 '15 at 15:22
  • Title is not a valid attribute for the img tag in the Html5 spec. – Funk Doc Aug 20 '15 at 15:27
  • 1
    Just use `basename($image)` and use a counter inside your foreach loop and echo `
    ` (or whatever you want) each 5th pass.
    – hellcode Aug 20 '15 at 15:27
  • It **is** going to repeat the file name. That is exactly what I'm trying to achieve. That is why I want the alt and title to match the image being pulled from the dir, not generic filler that all images share. – Sabrael Carroll Aug 20 '15 at 15:36

1 Answers1

0

Add this to your loop to get the name of the image without the file extension

<div class="row">
<?php $dirname = "cards/"; $images = glob($dirname . "*.png");  ?>
<?php foreach ($images as $image)  :?>
    <?php $title = pathinfo($image); ?>
    <div class="col-md-3">
      <img src="<?= $image ?>" alt="<?=title['filename']?>" class="img-thumbnail" >
    </div>
<?php endforeach ?>
</div>

as far as displaying 5 images per row you want to create pagination and return 5 images each time you click on the link. look for jQuery slider plugin.

Test produces the html markup below but only 4 images per row.

<div class="container">
    <div class="row">                           
        <div class="col-md-3">
            <img src="downloads/hex_bg_black.jpg" alt="hex_bg_black" class="img-thumbnail">
        </div>          
        <div class="col-md-3">
            <img src="downloads/zh_bg_1.jpg" alt="zh_bg_1" class="img-thumbnail">
        </div>
    </div>
</div>

Hope this help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
mdamia
  • 4,447
  • 1
  • 24
  • 23