Myuki
Myuki

Reputation: 13

Pulling an image from directory based on file name?

I'm trying to pull an image from a directory based on the file name matching the id number given in the URL. (ie: php?id=1 being the same as 1.png)

I've tried several different methods, and while I'm not getting any errors, I'm still getting no image that shows up when I type in the id tag.

Here's the most recent version of the code I've been working with:

       <?php

           $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

               $img = $id;
               foreach(glob("gallery3/var/albums/" . $img) as $filename) 
       ?>



    <img src = " <?php echo $filename; ?> " /> 

I'm at a loss. I've tried everything I can find and nothing seems to be working. I really don't want to pull the images from the database, and would prefer to pull them straight from the directory so that future uploaded images will be accessible directly from their id tag.

Upvotes: 1

Views: 43

Answers (2)

K Holmes
K Holmes

Reputation: 5

You could also go for:

<?php
if(isset($_GET['id']) && !empty($_GET['id']) && is_numeric($_GET['id'])) {
  echo "<img src='gallery3/var/albums/".$_GET['id'].".png'/>";
}
else {
  echo "Not Valid!";
}
?>

In the else statement at the bottom you could implement some form of error checking to present to the user in the event that a non valid input is received.

Upvotes: 0

Mattigins
Mattigins

Reputation: 1016

I think you're over-complicating it. All you need is this

<?php
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $img = $id;
?>
<img src="gallery3/var/albums/<?php echo $img; ?>.png" /> 

Upvotes: 1

Related Questions