Sunday, February 1, 2015

Output image file content using PHP with correct header for cache control (using etag and last-modified)

Creating code to read and output image content using PHP is easy. However it takes a little bit more PHP-fu to make your code to communicate with browser so cache can be used effectively.

What do I mean by that?  we will generate additional headers like:

Cache-control: public
Last-Modified:  ....
Etag:  ....


and we will check if browser provide us with HTTP_IF_MODIFIED_SINCE and HTTP_IF_NONE_MATCH to be compared against current file content to check if file_content have changed.

If the current file content is the same we will delivery

HTTP/1.1 304 Not Modified

if content is NOT the same, we will deliver the actual content of the file.

Here is the my code snippet to accomplish this:



Enjoy!

No comments:

Post a Comment