核心代碼 img.php
<?php
/**
* 隨機顯示圖片
* 用法: <img src="img.php"> 或 <img src="img.php?folder=images2/">
*/
$folder = isset($_GET['folder']) ? $_GET['folder'] : '/images/';
$path = $_SERVER['DOCUMENT_ROOT'] . '/' . $folder;
$files = [];
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file !== '.' && $file !== '..') {
$ext = strtolower(substr($file, -3));
if ($ext === 'gif' || $ext === 'jpg') {
$files[] = $file;
}
}
}
closedir($handle);
}
if (empty($files)) {
header('HTTP/1.1 404 Not Found');
exit;
}
$random = rand(0, count($files) - 1);
$file = $files[$random];
$ext = strtolower(substr($file, -3));
header($ext === 'gif' ? 'Content-type: image/gif' : 'Content-type: image/jpeg');
readfile("$path/$file");
使用方式
<!-- 預設讀取 /images/ 目錄 -->
<img src="img.php" alt="隨機圖片" />
<!-- 指定子目錄 -->
<img src="img.php?folder=uploads/photos/" alt="相簿隨機圖" />
進階優化建議
- 快取控制:添加
header('Cache-Control: max-age=3600') 減少伺服器壓力。
- 支援更多格式:擴展副檔名判斷至
png、webp 等。
- 防止目錄遍歷:對
$_GET['folder'] 嚴格過濾,禁止 ../ 等路徑。
- 效能提升:大量圖片時,建議預先掃描生成檔案列表快取(JSON/Redis),避免每次
opendir。