【phpstudy】php 动态输出图片 http header 304 状态

时间:2020-08-23  来源:J2EE/EJB/服务器  阅读:

什么是304 状态

如果客户端发送了一个带条件的GET 请求且该请求已被允许,而文档的内容(自上次访问以来或者根据请求的条件)并没有改变,则服务器应当返回这个304状态码。简单的表达就是:客户端已经执行了GET,但文件未变化。

php 动态输出图片为什么要输入304

客户端是怎么知道这些内容没有更新的呢?其实这并不是客户端的事情,而是你服务器的事情,大家都知道服务器可以设置缓存机制,这个功能是为了提高网站的访问速度,当你发出一个GET请求的时候服务器会从缓存中调用你要访问的内容,这个时候服务器就可以判断这个页面是不是更新过了,如果没有更新过那么他会给你返回一个304状态码。


有时候需要是用php动态生成图片,比如 多个比例的缩略图

但是是用php生成的图片的header 头部状态都是200,不能被缓存,这显然也不太合适。

可以如何通过缓存PHP生成的图像。此功能只检查头,看看图像是否是最新的,并发送304代码,如果是这样,那么浏览器将使用缓存的版本,而不是下载新的。否则新的图像输出到浏览。

php 动态输出图片 http header 304 代码


// 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");
 
?>

【phpstudy】php 动态输出图片 http header 304 状态

http://m.bbyears.com/jsp/94245.html

推荐访问:phpstorm php面试题 php数组转字符串 php教程
相关阅读 猜你喜欢
本类排行 本类最新