超级简单PHP实现随机图片功能代码 HTML/PHP 第1张

方法一:

PHP 随机图像实现的代码超级简单,短短四行就搞定了:随机显示指定文件夹下图片的方法

<?php
$img_array = glob('images/*.{gif,jpg,png,jpeg,webp,bmp}', GLOB_BRACE);
if(count($img_array) == 0) die('没找到图片文件。请先上传一些图片到 '.dirname(__FILE__).'/images/ 文件夹');
header('Content-Type: image/png');
echo(file_get_contents($img_array[array_rand($img_array)]));
?>

以上的代码会查找 images 目录下的所有图片,并随机挑选出一张显示出来。

方法二:随机显示指定文件夹下图片的方法

此代码会从指定的服务器文件夹随机选择一个图片进行显示

<?php 
//This will get an array of all the gif, jpg and png images in a folder 
$img_array = glob("img/*.{gif,jpg,png,jpeg,webp,bmp}",GLOB_BRACE); 
//Pick a random image from the array 
$img = array_rand($img_array); 
//Display the image on the page 
echo '<img alt="'.$img_array[$img].'" src="'.$img_array[$img].'" />'; 
?>

方法三:

设置文件名和数组,这些文件名与您要随机化的图像的文件名相对应。

<?php
  $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames
 
  $i = rand(0, count($bg)-1); // generate random number size of the array
  $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

<head>中CSS

通常,您希望将CSS保留在HTML之外,但我们仅在此处使用它来回显我们在上面选择的随机文件名。

<style type="text/css">
body{
background: url(images/<?php echo $selectedBg; ?>) no-repeat;
}
</style>

 

发表回复

后才能评论