什麼是304 狀態
如果用戶端發送了一個帶條件的GET 請求且該請求已被允許,而文檔的內容(自上次訪問以來或者根據請求的條件)並沒有改變,則伺服器應當返回這個304狀態代碼。簡單的表達就是:用戶端已經執行了GET,但檔案未變化。
php 動態輸出圖片為什麼要輸入304
用戶端是怎麼知道這些內容沒有更新的呢?其實這並不是用戶端的事情,而是你伺服器的事情,大家都知道伺服器可以設定緩衝機制,這個功能是為了提高網站的訪問速度,當你發出一個GET請求的時候伺服器會從緩衝中調用你要訪問的內容,這個時候伺服器就可以判斷這個頁面是不是更新過了,如果沒有更新過那麼他會給你返回一個304狀態代碼。
有時候需要是用php動態產生圖片,比如 多個比例的縮圖
但是是用php產生的圖片的header 頭部狀態都是200,不能被緩衝,這顯然也不太合適。
可以如何通過緩衝PHP產生的映像。此功能只檢查頭,看看映像是否是最新的,並發送304代碼,如果是這樣,那麼瀏覽器將使用緩衝的版本,而不是下載新的。否則新的映像輸出到瀏覽。
php 動態輸出圖片 http header 304 代碼
<?php
// return the browser request header
// use built in apache ftn when PHP built as module,
// or query $_SERVER when cgi
function getRequestHeaders()
{
if (function_exists("apache_request_headers"))
{
if($headers = apache_request_headers())
{
return $headers;
}
}
$headers = array();
// Grab the IF_MODIFIED_SINCE header
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']))
{
$headers['If-Modified-Since'] = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
}
return $headers;
}
// Return the requested graphic file to the browser
// or a 304 code to use the cached browser copy
function displayGraphicFile ($graphicFileName, $fileType='jpeg')
{
$fileModTime = filemtime($graphicFileName);
// Getting headers sent by the client.
$headers = getRequestHeaders();
// Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) &&
(strtotime($headers['If-Modified-Since']) == $fileModTime))
{
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).
' GMT', true, 304);
}
else
{
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $fileModTime).
' GMT', true, 200);
header('Content-type: image/'.$fileType);
header('Content-transfer-encoding: binary');
header('Content-length: '.filesize($graphicFileName));
readfile($graphicFileName);
}
}
//example usage
displayGraphicFile("./images/image.png");
?>