Static images have correct headers – Apache sends them by default. Different story is with all dynamic generating content – if you don’t send correct headers user’s browser will load it every time. It’s not always good, because generated thumbnails doesn’t change every time and should be cached in browser’s cache. If you want to reduce server load and increase loading speed you definitely need to send correct headers.
Our task is to give browser enough information to identify content, which later can be used to decided if content has changed, and if not – say it to browser without sending content again. Bigger picture is explained here, I really recommend analysing it a little bit – it gives better understanding how headers work and what they mean.
As you saw in headers map, there are many possible headers to send, but we can focus on three of them:
- Etag. Unique identified for output data (maybe hash)
- Last-Modified. Date of last data modification
- Expires. When to expire content
Constructing algorithm is pretty simple, it can be explained in pseudo-code:
get request headers
is content expired
send content, new headers
else is content different (Etag)
send content, new headers
else
304 header, no content
I’ve created outputCacheHeaders(…) function which (available here) outputs all required headers and returns true if you need to output content or false if not. All you need to do is pass modification time, live time and data (two last ones are not required). Live time says how long should cache be kept and data is used to generate Etag. Very simple!
After enabling correct headers sending, my websites started to feel much faster, because HTTP requests takes much less time. Also, Yahoo performance tips are really worth reading, really. There are many great tips and I have been using many of them for a long time. These tricks are much much more significant than 0.1 s. faster PHP rendering time.







