using 'glob' to get all images from a directory

一笑奈何 提交于 2019-12-25 12:11:06

问题


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?


回答1:


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.




回答2:


You need to prepend the dirname to glob's result to get the full paths.

So something like:

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


来源:https://stackoverflow.com/questions/21518403/using-glob-to-get-all-images-from-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!