Caching HTTP files with PHP

16,000

Solution 1

You're right: somebody's already done that :)

PHP framework Symfony2 comes with a caching reverse proxy as part of its standard distribution. Docs here: http://symfony.com/doc/2.0/book/http_cache.html

Solution 2

Using a Reverse Proxy like Squid, Varnish or even Apache mod_cache would help you a lot regarding cache related HTTP headers. However if you need to have a full PHP version you should honor Cache-Control and then Expires because when Cache-Control and Expires are available in the same HTTP response Cache-Control takes precedence with the "max-age" attribute as described in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.3:

If a response includes both an Expires header and a max-age directive, the max-age directive overrides the Expires header, even if the Expires header is more restrictive. This rule allows an origin server to provide, for a given response, a longer expiration time to an HTTP/1.1 (or later) cache than to an HTTP/1.0 cache. This might be useful if certain HTTP/1.0 caches improperly calculate ages or expiration times, perhaps due to desynchronized clocks.

You should also be very careful with the "no-cache" attribute which is kind of misleading as it requires a revalidation with the origin server, so it is a bit like a "store-but-do-no-serve-from-cache-without-revalidation" header.

You can also ignore the Pragma header for two reasons:

  • it is a request header, not a response header
  • it is for HTTP 1.0 and the (almost entire) world is HTTP 1.1 now :)

'Hope that helps :)

Share:
16,000
cweiske
Author by

cweiske

Updated on June 04, 2022

Comments

  • cweiske
    cweiske almost 2 years

    I'm writing a library that requests files via HTTP and HTTPS. To reduce traffic to often requested URLs, I want to cache the retrieved files and respect their cache settings.

    Now the cache expiry seems to be a hard thing, because the HTTP RFC define so many of them that need to be checked in all possible combinations:

    • Expires
    • Cache-Control (with dozens of possible values)
    • Pragma

    I can imagine that someone already wrote PHP code that implements all that stuff correctly. Where is it?