当前位置:首页 > PHP教程 > PHP常见问题

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

有时一些静态文件(如图片)会由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;
    }
}

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



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!