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

PHP Session 緩存控制函數 session_cache_limiter 與 session_cache_expire 詳解

     編輯:PHP 相關知識

函數作用速覽

函數作用參數返回值
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);

關鍵注意事項

  1. 必須在 session_start() 之前調用,否則無效。
  2. 每次請求都需重新設置,因為 PHP 請求開始時會重置為默認值。
  3. session_cache_expire 單位是**分鐘**,非秒。
  4. 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 實現協商緩存
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved