PHP static file return

Source: Internet
Author: User
Tags browser cache

sometimes some static files (such as pictures) will be output by PHP, will find that the request is 200, the static file every time to the server to request too waste of resources, then how to let the browser cache pictures? We need to output 304 in PHP.

We can use the http_if_modified_since in PHP to combine etag to do this. ETag does not specify the format, we can use the file to modify the time of the MD5 value, the code is as follows:

The code is as follows:

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

}

}

You can call it before you output it in a static file, such as a picture, in your code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.