部落格側邊欄隨機圖片、廣告輪播、簽名檔隨機圖、驗證碼背景等。
/images/)。Content-Type Header。
readfile() 輸出圖片二進制內容。<?php
/**********************************************
* 隨機圖片輸出腳本
* 用法:
或
**********************************************/
// 1. 目錄參數處理
$folder = isset($_GET['folder']) ? $_GET['folder'] : '/images/';
// 安全:防止目錄遍歷攻擊
$folder = str_replace(array('../', '..\\'), '', $folder);
if (strpos($folder, '/') !== 0) $folder = '/' . $folder;
$path = $_SERVER['DOCUMENT_ROOT'] . $folder;
if (!is_dir($path)) {
header('HTTP/1.0 404 Not Found');
exit('Directory not found');
}
// 2. 掃描圖片檔案
$files = array();
$allowedExt = array('jpg', 'jpeg', 'gif', 'png', 'webp');
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') continue;
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($ext, $allowedExt)) {
$files[] = $file;
}
}
closedir($handle);
}
if (empty($files)) {
header('HTTP/1.0 404 Not Found');
exit('No images found');
}
// 3. 隨機選取並輸出
$random = array_rand($files);
$selected = $files[$random];
$filePath = $path . '/' . $selected;
// 發送正確 MIME
$ext = strtolower(pathinfo($selected, PATHINFO_EXTENSION));
$mime = array(
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'webp' => 'image/webp'
);
header('Content-Type: ' . $mime[$ext]);
header('Content-Length: ' . filesize($filePath));
// 可選:快取控制
header('Cache-Control: public, max-age=3600');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
readfile($filePath);
?>
opendir/readdir 較慢,建議預先建立圖片清單資料庫/快取(JSON/Redis),隨機抽取路徑再 readfile。X-Accel-Redirect Header,大幅降低 PHP 進程佔用。