php 動態輸出圖片 http header 304 狀態

來源:互聯網
上載者:User

什麼是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");
 
?>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.