简体   繁体   中英

Using glob to dynamically display images with different extensions not working in PHP

my first question here... I'm trying to display the images dynamically from a folder inside a " fotorama " div. With this code:

<?php
$dir = "/example/images/category/";
$images = glob($dir.'*.{JPG,jpg,gif,png,bmp}', GLOB_BRACE);
foreach ($images as $image) {
echo "<img src='".$dir.".".$image."' />";
};?>

I know this have been asked before; but after reading everything I found: For example ( here , here and here ) plus many other "similar" questions. They all recommend pretty much the same code (with slight differences in syntax between each other) I've tried every variant of this code I've found but it displays nothing.

I know the ($dir) is fine, because when I try: echo '<img src="'.$dir."img1.jpg".'">'; It displays that particular image. The problem must be in the glob part because when I use var_dump($images); before the foreach loop it shows this: array (0) {}.

I don't know what is the problem...

Edit: With help from Sam's answer, the code now works I found out I had forgotten to correct something in the GLOB_BRACE part. The corrected code should be something like this:

<?php
$dir = "c:/xampp/htdocs/example/images/category/";
$images = glob($dir.'*.{JPG,jpg,gif,png,bmp}', GLOB_BRACE);
foreach ($images as $image) {
echo "<img src='".$image."' />";
};
?>

For future reference the path on Xampp localhost for the glob() function to work is: C:/xampp/htdocs/your-folder-structure

glob() looks for a filesystem path, whereas the src attribute of the image tag is pointing at a url location, probably relative to your docroot (but could be anywhere depending on your routing rules).

So, for example, if the /example/images/ url points to /var/www/example/images/ on the filesystem, you'd want to do:

<?php
$dir = "/var/www/example/images/category/";
$url = "/example/images/category/";
$images = glob($dir.'*.{JPG,jpg,gif,png,bmp}', GLOB_BRACE);
foreach ($images as $image) {
    echo "<img src='{$url}{$image}' />";
};?>

You'll need to figure out where on the filesystem that directory is in your specific case though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM