萬盛學電腦網

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

PHP 隨機頭像實作:從簡易版到目錄掃描完整版

版本一:極簡單檔版(固定命名)

假設目錄下有 0.jpg ~ 5.jpg 六張圖:

<?php readfile(rand(0,5).'.jpg'); ?>

缺點: 檔名固定、無法動態增減、無 Content-Type 設定。

版本二:目錄掃描完整版(推薦)

<?php
$url = 'pic';  // 圖片目錄(相對路徑)
$files = array();

if ($handle = opendir($url)) {
    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.0 404 Not Found");
    exit('No images found');
}

$random = rand(0, count($files) - 1);
$selected = $files[$random];
$ext = strtolower(substr($selected, -3));

// 正確輸出 Content-Type
if ($ext === 'gif') {
    header("Content-Type: image/gif");
} elseif ($ext === 'jpg' || $ext === 'jpeg') {
    header("Content-Type: image/jpeg");
} else {
    header("Content-Type: application/octet-stream");
}

readfile("$url/$selected");
?>

關鍵改進點

  1. 動態掃描目錄:新增/刪除圖片無需改代碼
  2. 副檔名驗證:只處理 gif/jpg,避免輸出非圖片檔
  3. 正確 Content-Type:瀏覽器正確渲染、快取
  4. 空目錄處理:回傳 404 而非報錯
  5. 大小寫不敏感:strtolower() 處理副檔名

進階擴充建議

  • 快取機制:ETag/Last-Modified/Cache-Control 減少頻繁讀取
  • 權重隨機:陣列值設為 ['file.jpg'=>10, 'rare.jpg'=>1] 實現機率控制
  • 分類隨機:子目錄分類,傳參 ?cat=male 選擇目錄
  • 圖片處理:整合 GD/Imagick 即時縮圖、水印
  • 資料庫驅動:大量圖片時用 DB 存路徑、標籤、權重

HTML 引用方式

<img src="random_avatar.php" alt="隨機頭像" />
<img src="random_avatar.php?cat=female" alt="女性頭像" />

安全性提醒

⚠️ readfile() 直接輸出檔案內容,確保 $url 目錄不可上傳執行腳本,防止任意檔案讀取漏洞。生產環境建議:

  • 將圖片目錄放在 public 外
  • 驗證 $selected 不含路徑遍歷字元(../)
  • 使用 basename() 確保只取檔名
copyright © 萬盛學電腦網 all rights reserved