php---header函數設置瀏覽器緩存

這涉及到4種頭標類型: 

Last-Modified(最後修改時間); 
Expires(有效期限); 
Pragma(編譯指示); 
Cache-Control(緩存控制); 
前三個頭標屬於HTTP1.0標準。頭標Last-Modified使用UTC日期時間值。若是緩存系統發現Last-Modified值比頁面緩存版本的更接 
近當前時間,他就知道應該使用來自服務器的新版本。 

Expires 代表了緩存版本什麼時候應該過時(格林威治標準時間)。把它設置爲一個之前的時間就會強制使用服務器上的頁面。 

Pragma生命了頁面數據應該如何被處理。能夠這樣避免對頁面進行緩存: 

header("Pragma:no-cache"); 

Cache-Control 頭標是在HTTP1.1裏添加的,可以實現更細緻的控制(還應該繼續使用HTTP1.0頭標)。Cache-Control的設置有 

不少,以下表: php

指令                                 含義html

public                              能夠在任何地方緩存mysql

private                             只能被瀏覽器緩存sql

no-cache                         不能在任何地方緩存數據庫

must-revalidate                緩存必須檢查更新版本瀏覽器

proxy-revalidate               代理緩存必須檢查更新版本緩存

max-age                           內容可以被緩存的時期,以秒錶示服務器

s-maxage                         覆蓋共享緩存的max-age設置函數

下面實例利用header()設置瀏覽器的緩存:fetch

<?php # Script 2.7 - view_tasks.php 
// Connect to the database: 
$dbc = @mysqli_connect ('localhost', 'username', 'password', 'test') OR die ('<p>Could not connect to the database!</p></body></html>'); 
// Get the latest dates as timestamps: 
$q = 'SELECT UNIX_TIMESTAMP(MAX(date_added)), UNIX_TIMESTAMP(MAX(date_completed)) FROM tasks'; 
$r = mysqli_query($dbc, $q); 
list($max_a, $max_c) = mysqli_fetch_array($r, MYSQLI_NUM); 
// Determine the greater timestamp: 
$max = ($max_a > $max_c) ? $max_a : $max_c; 
// Create a cache interval in seconds: 
$interval = 60 * 60 * 6; // 6 hours 
// Send the header: 
header ("Last-Modified: " . gmdate ('r', $max)); 
header ("Expires: " . gmdate ("r", ($max + $interval))); 
header ("Cache-Control: max-age=$interval"); 
?>

1.鏈接數據庫後獲取數據表中最新的日期值date_added,date_completed,用UNIX_TIMESTAMP()函數將返回值轉化爲整數而後獲取最大值賦予$max。 

2.定義一個合理緩存時間。 

$interval=60*60*6 

合理值屈居於頁面自己、訪問者的數量和頁面的更新頻率,以上代碼爲6個小時

3.發送Last-Modified頭標。 

header("Last-Modified:".gmdate("r",($max+$interval))); 

gmdate()函數使用了參數"r"時,會根據HTTP規範返回相應的日期格式。 

4.設置Expires頭標。

header ("Expires: " . gmdate ("r", ($max + $interval))); 

5.設置Cache_Control頭標。 

header ("Cache-Control: max-age=$interval"); 

相關文章
相關標籤/搜索