萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 隨機顯示圖片三種實現方案:從簡單到生產級

方案一:固定數組 + rand() (最簡單)

$images = [
    '/images/banner1.jpg',
    '/images/banner2.jpg',
    '/images/banner3.jpg',
];
$random = $images[array_rand($images)];
echo "Random Banner";

適用:固定少量圖片、無需動態管理。

方案二:掃描目錄 + array_rand (動態目錄)

$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 "Random";
} else {
    echo "Default";
}

優點:新增/刪除文件即時生效。缺點:每次請求掃描目錄,高併發下 I/O 開銷大。

方案三:獨立圖片服務端點 (生產級推薦)

原理:<img src="/api/random-image?category=banner">,後端直接輸出圖片二進制,可控制緩存、防盜鏈、統計。

前端整合

<img src="/random-image.php?category=banner" alt="Random Banner" loading="lazy">

進階:分類權重、去重、A/B 測試

$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)。

copyright © 萬盛學電腦網 all rights reserved