php 动态输出图片 http header 304 状况
有许多的站长会把自己的图片利用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); } } //Cuoxin.com //example usage displayGraphicFile("./images/image.png"); ?> (编辑:银川站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |