首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 隨機顯示圖片功能實作:目錄掃描與 Header 輸出

     編輯:PHP 綜合知識

應用場景

部落格側邊欄隨機圖片、廣告輪播、簽名檔隨機圖、驗證碼背景等。

核心實作步驟

  1. 接收目錄參數(預設 /images/)。
  2. 掃描目錄,過濾副檔名(jpg、gif、png 等)。
  3. 隨機選取一個檔案。
  4. 依副檔名發送正確 Content-Type Header。
  5. 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。
  • 安全:嚴格過濾目錄參數,禁止存取 Web 根目錄外路徑;驗證檔案 MIME 而非僅靠副檔名。
  • 擴展:支援權重隨機、分類隨機、圖片尺寸參數動態縮放(結合縮略圖函數)。
  • Nginx X-Accel-Redirect:高併發下讓 Nginx 直接發送檔案,PHP 僅返回 X-Accel-Redirect Header,大幅降低 PHP 進程佔用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved