1·项目部署
根目录 /www/demo.com
2·创建文件
/www/demo.com/i/random/www/demo.com/i/random/random.php/www/demo.com/i/random/default/www/demo.com/i/random/xxxx3·random.php
<?php
// 设置站点地址及图片文件夹
$weburl = 'https://demo.com/i/random/';
$path = isset($_GET['path']) ? $_GET['path'] : 'default';
// 过滤 modifyLink 参数,确保只能是 true 或 false
$modifyLink = isset($_GET['modifyLink']) ? filter_var($_GET['modifyLink'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : false;
$modifyLink = $modifyLink === true ? true : false;
function getImagesFromDir($path) {
$images = array();
if ($img_dir = @opendir($path)) {
while (false !== ($img_file = readdir($img_dir))) {
if (preg_match("/(\.gif|\.jpg|\.png|\.webp)$/i", $img_file)) {
$images[] = $img_file;
}
}
closedir($img_dir);
}
return $images;
}
function getRandomFromArray($ar) {
if (empty($ar)) {
return null; // 防止数组为空时报错
}
mt_srand((double) microtime() * 10000000);
$num = array_rand($ar);
return $ar[$num];
}
$imgList = getImagesFromDir($path);
$img = getRandomFromArray($imgList);
if (!$img) {
// 如果没有找到图片,返回 404
header("HTTP/1.0 404 Not Found");
exit("No images found in the directory.");
}
$imageUrl = $weburl . $path . '/' . $img;
if ($modifyLink) {
// **方式 1:使用 302 重定向到图片链接**
header("Location: $imageUrl");
exit;
} else {
// 直接显示 HTML 页面,展示图片
echo '<html><head><style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
background-color: #000; /* Optional: Set a background color */
}
img {
max-width: 100%;
max-height: 100vh;
object-fit: contain;
}
</style></head><body>';
echo '<img src="' . $imageUrl . '" alt="Random Image" />';
echo '</body></html>';
}
?>4·使用
使用默认default图库
https://demo.com/i/random/index.php使用xxxx
https://demo.com/i/random/index.php?path=xxxxhttps://demo.com/i/random/index.php?path=xxxx,xxxx无返回链接
https://demo.com/i/random/index.php?modifyLink=false&path=xxxx返回链接
https://demo.com/i/random/index.php?modifyLink=true&path=xxxx- 测试链接(无返回):
点击这里
测试链接(返回):点击这里
