views:

33

answers:

1

Serve the new content only if the file has changed since last visit.

How do I implement that?

UPDATE

Sorry not to mention it earlier,but the requested resource is web page which is requested directly,not an image.

+2  A: 

You can use a trick borrowed from rails and append the last file modification time to the include:

$fileName = 'image.jpg';
$httpLink = $fileName . '?' . filemtime( $fileName );
echo '<img src="', $fileName, '" alt="blah" />';

This will output a link like

<img src="image.jpg?1002412" alt="blah" />   

Then when the file changes, the query string will also change and the browser will request the "new" file i.e.

<img src="image.jpg?1003622" alt="blah" />

Alternatively you could keep a local log of file revisions and read the revision number from a database rather than the filesystem, which may be marginally faster (and save filesystem reads, although it's not significant difference - dependant on db vs web server load).

Andy
Hey, what a nifty idea! `filemtime` is also pretty easy on performance. Nice!
Pekka
Now that is one awesome trick, didn't know about that :O
lamas
This will work **much** better if you use PATH_INFO instead (browsers might be picky if the URL doesn't end with an extension).
Lo'oris
But this won't work for me,because the page is requested directly, and what I want to cache is the page,not image.
also, *please*, don't **ever** use `.jpg`, that's a DOS evilness. Use full `.jpeg`.
Lo'oris
@Lo'oris used this in production with no problem, PATH_INFO doesn't provide a modified file time. Could you provide an example?
Andy
@user198729 could you update your question then? You don't mention what type of data you're serving.
Andy