#方法一
将下面代码保存为 xxxx.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文件夹存放图片。
访问你的 https://网址/xxxx.php 就会随机图片了
#方法二
直接将图片写进文件,复制下面代码 保存为 xxx.php 就可以了
php通过rand()函数产生随机数,这个函数可以产生一个指定范围的数字
这段代码通过产生的随机数,随机选择图片
<html>
<body>
<?php
srand( microtime() * 1000000 );
$num = rand( 1, 4 );
switch( $num )
{
case 1: $image_file = "/home/images/alfa.jpg";
break;
case 2: $image_file = "/home/images/ferrari.jpg";
break;
case 3: $image_file = "/home/images/jaguar.jpg";
break;
case 4: $image_file = "/home/images/porsche.jpg";
break;
}
echo "Random Image : <img src=$image_file />";
?>
</body>
</html>
#方法三
新建xxxxx.php文件把下面代码放进去,然后同一目录下创建个img.txt文件把图片链接加在里面,如下面图片那样放,一行一个连接。
<?php
//存有美图链接的文件名img.txt
$filename = "img.txt";
if(!file_exists($filename)){
die('文件不存在');
}
//从文本获取链接
$pics = [];
$fs = fopen($filename, "r");
while(!feof($fs)){
$line=trim(fgets($fs));
if($line!=''){
array_push($pics, $line);
}
}
//从数组随机获取链接
$pic = $pics[array_rand($pics)];
//返回指定格式
$type=$_GET['type'];
switch($type){
//JSON返回
case 'json':
header('Content-type:text/json');
die(json_encode(['pic'=>$pic]));
default:
die(header("Location: $pic"));
}
?>
#另外用法
创建一个html包含随机图api,返回不一样的图片展示。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>demo</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () {
for (var i = 0; i < 5; i++) {
let d = new Date(),
r = Math.round(Math.random() * 100000);
$("body").append(`
<img src="/demo/random.php?r=${d.getTime() + r.toString()}" alt="demo">//修改为自己的随机图https://xxxx.random.php 或其他名称
`);
}
});
</script>
</body>
</html>