Home > Backend Development > PHP Tutorial > php静态文件返回304技巧分享_PHP

php静态文件返回304技巧分享_PHP

WBOY
Release: 2016-05-31 13:18:19
Original
839 people have browsed it

有时一些静态文件(如图片)会由php输出,会发现请求都是200,静态文件每次都去服务器上请求太浪费资源了,这时如何让浏览器缓存图片呢?就需要我们在php中输出304了。

我们可以利用php中的 HTTP_IF_MODIFIED_SINCE 结合etag来干这事。Etag没有明确规定的格式,我们可以用文件修改时间的md5值,代码如下:

代码如下:


private function _addEtag($file) {
    $last_modified_time = filemtime($file);
    $etag = md5_file($file);
    // always send headers
    header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
    header("Etag: $etag");
    // exit if not modified
    if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
    @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
        header("HTTP/1.1 304 Not Modified");
        exit;
    }
}

在代码中可以在静态文件(如图片)输出之前调用即可。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template