我在网站上打印随机图像的代码出了什么问题


What is wrong with my code on printing a random image in a website?

这是在我的网站上显示随机图像的代码,但由于某种原因,图像没有弹出,并且声明$rand_image的行出现错误。错误显示未定义索引。我在目录中有7个图像。

$imagesDir = ''socimages'Badminton'; // my image directory
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); // glob
$rand_image = $images[array_rand($images)]; // applying the random function
...
...
<img src="<?php echo $rand_image[0];?>"< alt="" height="246" width="246"></p></div>

$rand_image已经是不需要$rand_image[0]的图像;

<img src="<?php echo htmlspecialchars($rand_image);?>"< alt="" height="246" width="246"></p></div>

此外,$rand_image可能是磁盘上的路径,而不是web可访问的路径,因此您需要对其进行映射。

我会做这样的事情。

$imagesDir = '/socimages/Badminton/'; // my image directory
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE); // glob
if ($images !== FALSE) {
   $rand_image = $images[array_rand($images)]; // applying the random function
} else {
   die("This thang ain't working, yo.");
}
...
...
<img src="<?php echo $rand_image;?>"< alt="" height="246" width="246"></p></div>