動態生成圖片 (驗證碼、圖表、縮圖、浮水印) 若無緩存策略,每次請求都會觸發 PHP 腳本執行、GD 運算、數據庫查詢,造成帶寬浪費與伺服器負載。HTTP 協議提供的 條件請求 機制 (Last-Modified / ETag + If-Modified-Since / If-None-Match) 可讓瀏覽器在資源未變時直接使用本地緩存,返回 304 Not Modified,僅傳輸幾百字節 Header。
<?php
// 必須在任何輸出前設置
session_start(); // 若需 Session 配合
// 1. 強制私有緩存,禁止代理服務器緩存 (含用戶敏感信息時)
header('Cache-Control: private, max-age=10800, pre-check=10800'); // 3 小時
header('Pragma: private'); // HTTP/1.0 兼容
// 2. 設定過期時間 (RFC 822 格式)
header('Expires: ' . date(DATE_RFC822, strtotime('+2 days')));
// 3. 最後修改時間 (關鍵:需反映圖片內容實際變更時間)
$imagePath = 'chart.png';
$lastModified = filemtime($imagePath); // 或數據庫記錄的更新時間
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
// 4. 實體標籤 (ETag) - 更精確的變更檢測
$etag = md5_file($imagePath); // 或 hash_file('sha256', $imagePath)
header('ETag: "' . $etag . '"');
// 5. 圖片 Content-Type (必須在緩存 Header 之後)
header('Content-Type: image/png'); // 根據實際格式調整
<?php
$imagePath = 'chart.png';
$lastModified = filemtime($imagePath);
$etag = md5_file($imagePath);
// 設置緩存 Header (同上)
header('Cache-Control: private, max-age=3600');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
header('ETag: "' . $etag . '"');
header('Content-Type: image/png');
// 檢查 If-Modified-Since
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$clientTime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
if ($clientTime >= $lastModified) {
header('HTTP/1.1 304 Not Modified');
header('Content-Length: 0');
exit;
}
}
// 檢查 If-None-Match (ETag 優先級更高)
if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$clientEtag = str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH']);
if ($clientEtag === $etag) {
header('HTTP/1.1 304 Not Modified');
header('Content-Length: 0');
exit;
}
}
// 讀取並輸出圖片內容
readfile($imagePath); // 比 file_get_contents + echo 更省記憶體
<?php
class ImageCacheResponse {
private string $filePath;
private string $mimeType;
private int $maxAge;
private bool $useEtag;
public function __construct(string $filePath, int $maxAge = 3600, bool $useEtag = true) {
if (!file_exists($filePath) || !is_readable($filePath)) {
throw new InvalidArgumentException("圖片文件不存在或不可讀: $filePath");
}
$this->filePath = $filePath;
$this->maxAge = $maxAge;
$this->useEtag = $useEtag;
$this->mimeType = $this->detectMimeType();
}
public function send(): void {
$lastModified = filemtime($this->filePath);
$etag = $this->useEtag ? md5_file($this->filePath) : null;
// 發送緩存 Header
$this->sendCacheHeaders($lastModified, $etag);
// 處理條件請求
if ($this->handleConditionalRequest($lastModified, $etag)) {
return; // 已發送 304 並 exit
}
// 發送內容
$this->sendContent();
}
private function sendCacheHeaders(int $lastModified, ?string $etag): void {
header('Cache-Control: private, max-age=' . $this->maxAge);
header('Pragma: private');
header('Expires: ' . date(DATE_RFC822, time() + $this->maxAge));
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
if ($etag) header('ETag: "' . $etag . '"');
header('Content-Type: ' . $this->mimeType);
header('Content-Length: ' . filesize($this->filePath));
header('Accept-Ranges: bytes'); // 支援斷點續傳
}
private function handleConditionalRequest(int $lastModified, ?string $etag): bool {
// ETag 優先 (強驗證器)
if ($etag && isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
$clientEtag = str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH']);
if ($clientEtag === $etag) {
$this->send304();
return true;
}
}
// Last-Modified 降級 (弱驗證器)
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
$clientTime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
if ($clientTime >= $lastModified) {
$this->send304();
return true;
}
}
return false;
}
private function send304(): void {
header('HTTP/1.1 304 Not Modified');
header('Content-Length: 0');
// 保留緩存 Header 讓瀏覽器更新過期時間
exit;
}
private function sendContent(): void {
// 大文件分塊輸出,避免佔用過多記憶體
$handle = fopen($this->filePath, 'rb');
while (!feof($handle)) {
echo fread($handle, 8192);
flush(); // 可選:分塊發送
}
fclose($handle);
}
private function detectMimeType(): string {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $this->filePath);
finfo_close($finfo);
return $mime ?: 'application/octet-stream';
}
}
// 使用範例
$response = new ImageCacheResponse('/var/www/images/chart.png', 86400); // 緩存 1 天
$response->send();
若圖片由 GD 即時生成 (如驗證碼、即時圖表),無 filemtime,可用內容哈希作為 ETag,業務版本號/時間戳作為 Last-Modified:
<?php
// 動態生成圖片邏輯...
$imageData = generateChartImage($params); // 返回二進制字符串
$etag = md5($imageData);
$version = $params['version'] ?? 1; // 業務版本
$lastModified = strtotime($params['updated_at'] ?? 'now');
header('Cache-Control: private, max-age=300'); // 5 分鐘
header('ETag: "' . $etag . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
header('Content-Type: image/png');
// 條件檢查 (同上)
if (($etag && isset($_SERVER['HTTP_IF_NONE_MATCH']) && str_replace('"','',$_SERVER['HTTP_IF_NONE_MATCH']) === $etag) ||
(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastModified)) {
header('HTTP/1.1 304 Not Modified');
header('Content-Length: 0');
exit;
}
echo $imageData;
若圖片為靜態文件,建議直接在 Web 服務器層面配置,效能更高:
# Nginx
location ~* \.(jpg|jpeg|png|gif|ico|webp)$ {
expires 30d;
add_header Cache-Control "public";
etag on;
last_modified on;
}
# Apache (.htaccess)
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
Header set Cache-Control "public"
FileETag MTime Size
Last-Modified/ETag + 條件請求檢查,返回 304 節省帶寬與 CPU。ETag 比 Last-Modified 更精確 (秒級 vs 內容級);Cache-Control: private 保護用戶隱私數據不被 CDN/代理緩存。curl -I -H "If-None-Match: ..." URL 命令行驗證。