Yoosuf
Yoosuf

Reputation: 892

Displaying Images from a folder in PHP

I am currently creating an e-commerce website where I retrieve the vehicle details from the database and search for its image in a folder. I used the code below for searching the folder for the image, but it only show the name of the JPG file and not the image of it. Could anyone help to to determine how I could display the image of the vehicle

$imageName=$_POST['car'];
if ($handle = opendir('Images/$imageName')) {
   $dir_array = array();
   while (false !== ($file = readdir($handle))) {
  if($file!="." && $file!=".."){
$dir_array[] = $file;
}
}    
echo $dir_array[rand(0,count($dir_array)-1)];
 closedir($handle);
}

Upvotes: 2

Views: 2978

Answers (3)

SteeveDroz
SteeveDroz

Reputation: 6156

Hmm... If you have the name of the JPG, use <img src="NAME_OF_THE_IMAGE.JPG" /> ...

Upvotes: 0

Mihai
Mihai

Reputation: 68

You have to put html tags around the result. Try:

echo "<img src='PATH_TO_IMAGE/".$dir_array[rand(0,count($dir_array)-1)]."'>";

where PATH_TO_IMAGE is the relative/absolute url address to your images folder

Ex

echo "<img src='/images/".$dir_array[rand(0,count($dir_array)-1)]."'>";

Upvotes: 2

Simon
Simon

Reputation: 37998

You need to print the path to the image inside an img HTML tag, otherwise it is just plain text.

echo '<img src="Images/' . $imageName . $dir_array[rand(0,count($dir_array)-1)] . '" alt="" />';

I hope you're doing some validation/sanitisation on $_POST['car'] somewhere?

Upvotes: 2

Related Questions