目录结构示例
实用的 PHP 随机图片实现方式,直接用就行。根据自己需要就图片存入images这个文件夹即可。
/images/
├─ 1.jpg
├─ 2.png
├─ 3.webp
└─ 4.gif
random.php
random.php
<?php
$dir = __DIR__ . '/images';
// 允许的图片格式
$allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$files = array_filter(scandir($dir), function ($file) use ($allowExt, $dir) {
if ($file === '.' || $file === '..') return false;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
return in_array($ext, $allowExt) && is_file($dir . '/' . $file);
});
// 随机一张
$img = $files[array_rand($files)];
// 输出图片
$path = $dir . '/' . $img;
$mime = mime_content_type($path);
header("Content-Type: {$mime}");
readfile($path);
exit;
使用方式
<img src="/random.php">
1 条评论
点赞