简体   繁体   中英

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);
}

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?

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)]."'>";

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

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