萬盛學電腦網

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

PHP 隨機顯示圖片功能實現:從簡單輪播到高效能 CDN 整合

基礎版:讀取目錄隨機輸出單張圖片

<?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 處理 → 高併發下 CPU/IO 瓶頸

解決方案:預生成清單 + 靜態文件 + Nginx 直接服務

<?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 配置:直接服務隨機圖片(無 PHP 介入)

# 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 高效能版:APCu 緩存文件列表

<?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);

前端整合:JavaScript 無刷新輪換

<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>

CDN 整合策略(生產環境推薦)

  1. 將圖片上傳至對象存儲(S3/OSS/COS/GCS)
  2. 配置 CDN 回源至對象存儲
  3. 使用 CDN Edge Function / Workers (Cloudflare Workers, AWS Lambda@Edge, 阿里云 EdgeRoutine) 實現邊緣隨機選擇:
    // 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);
      }
    }
  4. 前端直接請求 Worker URL,實現**零源站壓力、毫秒級響應、全球就近分發**

安全檢查清單

  • ☐ `realpath()` 防止目錄遍歷 (`../../etc/passwd`)
  • ☐ 白名單副檔名,拒絕 `.php`、`.html` 等可執行文件
  • ☐ `Content-Type` 根據副檔名/MIME 偵測設置,防 MIME 混淆攻擊
  • ☐ 禁用目錄執行權限:Nginx `location ~ \.php$ { deny all; }` 在圖片目錄
  • ☐ 設置 `X-Content-Type-Options: nosniff`

演進路徑:單機 `readfile` → APCu 緩存列表 → Nginx+Lua 邊緣分發 → CDN Edge Function。**核心原則:讓 PHP 盡量少參與靜態資源分發**。

copyright © 萬盛學電腦網 all rights reserved