有許多的站長會把自己的圖片利用php輸出來了這樣的話對于用戶來講沒有什么區別對于搜索引擎來講有一些區別了,如果我們沒有更新但輸入的還是不是304的話搜索引擎會認為圖片更新了,為了解決這個問題我們來看看如何處理吧.
什么是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);
- }
- } //Vevb.com
- //example usage
- displayGraphicFile("./images/image.png");
- ?>
新聞熱點
疑難解答