<?php
// random-image.php
// 用法:
$folder = $_GET['folder'] ?? 'images/';
$allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
// 安全:防止目錄遍歷攻擊
$basePath = realpath($_SERVER['DOCUMENT_ROOT'] . '/assets');
$targetPath = realpath($basePath . '/' . $folder);
if ($targetPath === false || strpos($targetPath, $basePath) !== 0) {
http_response_code(400);
exit('Invalid folder');
}
$files = [];
$dh = opendir($targetPath);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $allowedExt, true)) {
$files[] = $file;
}
}
closedir($dh);
if (empty($files)) {
http_response_code(404);
exit('No images found');
}
$randomFile = $files[array_rand($files)];
$filePath = $targetPath . DIRECTORY_SEPARATOR . $randomFile;
// 發送正確 Content-Type
$mimeTypes = [
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
];
$ext = strtolower(pathinfo($randomFile, PATHINFO_EXTENSION));
header('Content-Type: ' . ($mimeTypes[$ext] ?? 'application/octet-stream'));
header('Cache-Control: public, max-age=300'); // 瀏覽器快取 5 分鐘
header('Content-Length: ' . filesize($filePath));
readfile($filePath); // 高效輸出,不佔用 PHP 記憶體
<?php
// cron 每小時執行一次:generate-image-list.php
$folder = 'images/banner';
$basePath = '/var/www/assets';
$targetPath = $basePath . '/' . $folder;
$listFile = $basePath . '/.image-list-' . md5($folder) . '.json';
$files = [];
$dh = opendir($targetPath);
while (($file = readdir($dh)) !== false) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, ['jpg','jpeg','png','gif','webp'], true)) {
$files[] = $file;
}
}
closedir($dh);
file_put_contents($listFile, json_encode($files), LOCK_EX);
# nginx.conf
location /random-image/ {
# 由 Lua 腳本隨機選擇
access_by_lua_block {
local list_file = "/var/www/assets/.image-list-banner.json"
local files = cjson.decode(ngx.shared.image_list:get("banner") or '[]')
if #files == 0 then
-- fallback 讀取檔案
local f = io.open(list_file, "r")
if f then
files = cjson.decode(f:read("*a"))
f:close()
ngx.shared.image_list:set("banner", cjson.encode(files))
end
end
if #files > 0 then
local idx = math.random(#files)
ngx.var.random_image = files[idx]
else
return ngx.exit(404)
end
}
# 內部重導向到實際圖片
rewrite ^ /assets/banner/$random_image last;
}
location /assets/ {
alias /var/www/assets/;
expires 30d;
add_header Cache-Control "public";
}
※ 需安裝 OpenResty 或 Nginx + ngx_http_lua_module。
<?php
// random-image-fast.php
$folder = $_GET['folder'] ?? 'banner';
$cacheKey = "img_list:$folder";
$basePath = '/var/www/assets';
$targetPath = $basePath . '/' . $folder;
$files = apcu_fetch($cacheKey);
if ($files === false) {
$files = [];
$dh = opendir($targetPath);
while (($file = readdir($dh)) !== false) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, ['jpg','jpeg','png','gif','webp'], true)) {
$files[] = $file;
}
}
closedir($dh);
apcu_store($cacheKey, $files, 3600); // 快取 1 小時
}
if (empty($files)) { http_response_code(404); exit; }
$file = $files[array_rand($files)];
$filePath = $targetPath . DIRECTORY_SEPARATOR . $file;
// ETag / Last-Modified 支援條件請求
$etag = md5_file($filePath);
$lastMod = filemtime($filePath);
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
http_response_code(304);
exit;
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastMod) {
http_response_code(304);
exit;
}
header('Content-Type: ' . mime_content_type($filePath));
header('ETag: ' . $etag);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastMod) . ' GMT');
header('Cache-Control: public, max-age=300');
readfile($filePath);
<img id="randomBanner" src="/random-image.php?folder=banner" alt="Banner" style="width:100%;max-width:1200px;">
<script>
function refreshBanner() {
// 加時間戳防快取
document.getElementById('randomBanner').src = '/random-image.php?folder=banner&t=' + Date.now();
}
// 每 30 秒自動換圖
setInterval(refreshBanner, 30000);
// 手動換圖按鈕
document.getElementById('changeBtn')?.addEventListener('click', refreshBanner);
</script>
// Cloudflare Workers 範例
export default {
async fetch(request, env) {
const list = await env.IMAGES_KV.get('banner-list', {type: 'json'});
if (!list || !list.length) return new Response('Not found', {status: 404});
const img = list[Math.floor(Math.random() * list.length)];
return Response.redirect(`https://cdn.example.com/banner/${img}`, 302);
}
}
演進路徑:單機 `readfile` → APCu 緩存列表 → Nginx+Lua 邊緣分發 → CDN Edge Function。**核心原則:讓 PHP 盡量少參與靜態資源分發**。