Search code examples
phpfiledirectoryglob

using 'glob' to get all images from a directory


I'm trying to get all images from a directory and print them. I know my URL is correct because I am echoing the the $dirname along with a .jpg image I have saved in the directory. What am I doing wrong?

  <?php

  $dirname = "uploads/{$site_country}_{$site_state}_{$site_name}/{$record_id}/";
  $images = glob($dirname . "*.jpg");
  foreach($images as $image) {
  echo '<img src="'.$image.'"/>';
  }

  //check to see if $dirname is correct

  echo '<img src="' . $dirname . "IMG_0002.JPG" . '"/>';

  ?>

//edit

I have solved my problem, by removing the jpg extention and just pulling "*" for everything in the folder. Although it works for me now, its not best practice. It must be something to do with different .jpg file formats?


Solution

  • You used lowercase file extension here.

    $images = glob($dirname . "*.jpg");
    

    And uppercase JPG in your test output.

      echo '<img src="' . $dirname . "IMG_0002.JPG" . '"/>';
    

    If you're using a linux system then file extensions are case sensitive.