Php static file return 304 tip _ php instance

Source: Internet
Author: User
This article mainly shares a tips on returning 304 for php static files. If you need a friend, you can refer to the following: sometimes some static files (slices) will be output by php and you will find that all requests are 200, it is a waste of resources to request static files on the server every time. How can I cache images in the browser? We need to output 304 in php.

We can use HTTP_IF_MODIFIED_SINCE and etag in php to do this. Etag does not have a clearly defined format. We can use the md5 value of the file modification time. 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;
}
}

In the code, you can call it before the static file (slice) is output.

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.