利用 PHP 直接輸出圖片二進位資料,搭配 rand() 隨機選擇,即可實現「每次重整顯示不同大頭貼」的效果,無需 JavaScript、無需儲存多個靜態檔案。
0.gif、1.gif、2.gif。avatar.php:<?php
// avatar.php
$images = ['0.gif', '1.gif', '2.gif'];
$pick = $images[array_rand($images)]; // 或 rand(0,2)
header('Content-Type: image/gif');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
readfile($pick);
?>
avatar.php 與三張圖片上傳至支援 PHP 的主機同一目錄。https://yourdomain.com/path/avatar.php?.gif
尾端加 ?.gif 讓某些僅檢查副檔名的論壇系統通過驗證。
header('Content-Type: ' . mime_content_type($pick)) 自動判斷 MIME。array_fill 擴充陣列或自寫加權演算法。opcache、CDN 快取,或改用 Nginx try_files 直接導向靜態檔案。<?php
$dir = __DIR__ . '/avatars/';
$allowed = ['gif','png','jpg','jpeg','webp'];
$files = [];
foreach (glob($dir . '*.{'.implode(',',$allowed).'}', GLOB_BRACE) as $f) {
$files[] = $f;
}
if (!$files) {
http_response_code(404);
exit('No avatar images found');
}
$pick = $files[array_rand($files)];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $pick);
finfo_close($finfo);
header('Content-Type: ' . $mime);
header('Content-Length: ' . filesize($pick));
header('Cache-Control: public, max-age=300'); // 快取 5 分鐘
readfile($pick);
?>