php 输出图片头,php 动态输出图片 http header 304 状态

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

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值