search
Homephp教程php手册php静态文件返回304,

php静态文件返回304,

Jun 13, 2016 am 09:19 AM
phpDiscoverpicturedocumentaskoutputreturnstatic

php静态文件返回304,

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

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

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

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

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft