$images = [
'/images/banner1.jpg',
'/images/banner2.jpg',
'/images/banner3.jpg',
];
$random = $images[array_rand($images)];
echo "
";
適用:固定少量圖片、無需動態管理。
$dir = __DIR__ . '/uploads/banners/';
$allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$files = [];
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
if ($file === '.' || $file === '..') continue;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $allowed, true)) {
$files[] = $file;
}
}
closedir($dh);
if ($files) {
$random = $files[array_rand($files)];
echo "
";
} else {
echo "
";
}
優點:新增/刪除文件即時生效。缺點:每次請求掃描目錄,高併發下 I/O 開銷大。
原理:<img src="/api/random-image?category=banner">,後端直接輸出圖片二進制,可控制緩存、防盜鏈、統計。
<img src="/random-image.php?category=banner" alt="Random Banner" loading="lazy">
$weights = [
'banner1.jpg' => 50, // 50% 權重
'banner2.jpg' => 30,
'banner3.jpg' => 20,
];
// 展開權重數組
$pool = [];
foreach ($weights as $file => $w) {
$pool = array_merge($pool, array_fill(0, $w, $file));
}
$random = $pool[array_rand($pool)];
從固定數組到目錄掃描再到獨立服務端點,**架構演進方向是:關注點分離、緩存友好、可觀測、安全可控**。小項目用方案一/二,中大型項目必須走方案三並接入 CDN、對象存儲、圖片處理服務 (如 Thumbor、ImageKit、自建 Imagine/Intervention)。