user2773084
user2773084

Reputation: 107

Using glob() to display images, but images won't display

I'm working on an assignment that requires me to display all images from a server directory. I've tried implementing glob() to do this, and it appears to be nearly working, but for some reason the images don't appear. I'm using xampp to serve the page, and it's had no issues prior. I'm not sure what the problem could be. Below is the relevant code.

$size = 5;
$images = glob("../../ass1_data_stage2/jpg/*.JPG", GLOB_BRACE);
$width = (600 / $size);  

echo "<table><tr>"; 
for($i=1; $i < count($images); $i++) {
    if (($i % $size) == 0 and $i != 0) {
        echo "</tr><tr>"; 
    }

    $file = $images[$i]; 
    echo '<td><img src=$file width=$width."px" height="100px" alt="Random image" />   </td>'; 
}
echo "</tr>"; 

echo "</table>"; 

The output looks like this:

Upvotes: 0

Views: 735

Answers (2)

Matthew R.
Matthew R.

Reputation: 4350

I don't know if this is your exact issue, but your HTML syntax is incorrect for the image element:

echo '<td><img src=$file width=$width."px" height="100px" alt="Random image" /></td>';

Should be:

echo '<td><img src="'.$file.'" width="'.$width.'" height="100" alt="Random image" /></td>';

You could also use this method which is cleaner:

echo "<td><img src='{$file}' width='{$width}' height='100' alt='Random image' /></td>';

Upvotes: 1

Charaf JRA
Charaf JRA

Reputation: 8334

Here is a good example i used in one of my projects :

I suggest to use glob like this :

    $images = glob($path . '*.{jpg,jpeg,png,gif,JPG}', GLOB_BRACE);//only images

Example :

<?php

    $folder='name of your folder ';

    $path = 'uploads/'.$folder.'/' ;// slash in the end of path
    $images = glob($path . '*.{jpg,jpeg,png,gif,JPG}', GLOB_BRACE);//only images
    foreach ($images as $image) {
         echo "<img src='$image' />";
    }
?>

Upvotes: 0

Related Questions