什么是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");
?>
模拟极限越野
模拟极限越野开着大巴在各种奇葩路况里送乘客。山路弯道多得让人
模拟火车
模拟火车让你当回真正的火车司机,得先学会看信号灯、操作控制杆
可口的披萨美味的披萨
可口的披萨美味的披萨带您体验经营一家披萨店的乐趣。游戏画风温
定制虚拟偶像最新版
定制虚拟偶像最新版是一款超级经典有趣的日本模拟装扮类型的手游
病娇模拟器手机版正版(yandere simulator)
病娇模拟器最新版手游是一款萌妹二次元模拟游戏,玩家在游戏中可