函數作用速覽
| 函數 | 作用 | 參數 | 返回值 |
| session_cache_limiter() | 獲取/設置會話緩存控制模式 | 可選:public/private/no_cache/private_no_expire | 當前模式名 |
| session_cache_expire() | 獲取/設置會話頁面緩存過期時間(分鐘) | 可選:整數分鐘數 | 當前過期分鐘數 |
緩存模式詳解
<?php
// 必須在 session_start() 之前調用
// 1. public - 允許代理服務器緩存,客戶端緩存
session_cache_limiter('public');
// Expires: 未來時間,Cache-Control: public, max-age=...
// 2. private - 默認值,僅允許客戶端緩存,禁止代理緩存
session_cache_limiter('private');
// Cache-Control: private, max-age=..., pre-check=...
// 3. no_cache - 完全禁止緩存(安全敏感頁面)
session_cache_limiter('nocache');
// Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
// Pragma: no-cache
// Expires: 過去時間
// 4. private_no_expire - 私有緩存且不發送 Expires 頭
session_cache_limiter('private_no_expire');
?>
完整使用示例
<?php
// 設置緩存策略:私有,30 分鐘過期
session_cache_limiter('private');
session_cache_expire(30);
// 獲取當前設置
echo 'Cache Limiter: ' . session_cache_limiter() . '
';
echo 'Cache Expire: ' . session_cache_expire() . ' minutes
';
// 啟動會話
session_start();
// 輸出頁面內容
echo 'Session ID: ' . session_id();
文件下載場景專用設置
<?php
$file = 'report.pdf';
session_start();
session_cache_limiter('private'); // 允許瀏覽器緩存下載文件
session_cache_expire(60);
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Length: ' . filesize($file));
header('Pragma: public'); // 覆蓋 session 預設的 no-cache
header('Cache-Control: max-age=3600'); // 1小時
readfile($file);
關鍵注意事項
- 必須在
session_start() 之前調用,否則無效。
- 每次請求都需重新設置,因為 PHP 請求開始時會重置為默認值。
session_cache_expire 單位是**分鐘**,非秒。
- HTTPS 頁面建議使用
private 或 nocache,避免代理服務器緩存敏感內容。
現代替代:手動控制 Header
<?php
// 完全自定義緩存策略(不依賴 session 緩存控制)
header('Cache-Control: private, max-age=1800, must-revalidate');
header('Pragma: no-cache'); // HTTP/1.0 兼容
// 配合 ETag/Last-Modified 實現協商緩存
?>