PHP单文件实现随机图库
目录结构:
I------random image
I------index.php
I------images
I------computer
I------example.png
I------phones
I------avatars
I------covers
PHP文件
index.php
<?php
// 定义所有图片目录路径
$categories = [
'phone' => 'images/phones/',
'computer' => 'images/computers/',
'avatar' => 'images/avatars/',
'cover' => 'images/covers/'
];
// 获取URL参数中的类别
$type = isset($_GET['type']) ? $_GET['type'] : 'computer'; // 默认类型为phone
// 检查请求的类型是否存在于categories数组中
if (array_key_exists($type, $categories)) {
$categoryPath = $categories[$type];
// 获取选中类别目录下所有图片文件的列表
$images = glob($categoryPath . '*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
// 检查是否有图片文件存在
if (count($images) > 0) {
// 随机选择一个图片文件
$randomImage = $images[array_rand($images)];
// 重定向到选中的图片文件
header("Location: " . $randomImage);
exit;
} else {
// 如果没有找到图片,返回错误信息
header("HTTP/1.0 404 Not Found");
echo "No images found in the selected category.";
exit;
}
} else {
// 如果请求的类型不合法,返回错误信息
header("HTTP/1.0 400 Bad Request");
echo "Invalid category requested.";
exit;
}
?>文件夹
images(总图片文件夹)
computers(横图)
phones(竖图)
avatars(头像)
covers(封面)
访问方式
随机手机图片:https://localhost/index.php?type=phone
随机电脑图片:https://localhost/index.php?type=computer
随机头像图片:https://localhost/index.php?type=avatar
随机封面图片:https://localhost/index.php?type=cover
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 TAO
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果

