views:

35

answers:

4

I've been tasked to maintain a PHP website with a function which automatically generates RTF files and provides a link to download. Each time the previously generated file is overwritten by the new one.

However, it seems that upon attempting to download the generated file, the browser will sometimes retrieve a cached version which is normally different from the latest version (so you get the same document as last time rather than the one you requested).

I managed to work around this by giving each generated file a unique name based on the current timestamp but this generates lots of clutter in the directory which will need to be cleaned out periodically. Ideally I would like to tag this file such that the browser won't cache it and will get the latest version every time. How might I achieve this?

+4  A: 

Easiest way? Instead of linking to http://yoursite.com/file.rtf, link to http://yoursite.com/file.rtf?<?=time()?> . This will append a query string parameter which will vary each time the client requests it, and it won't therefore be cached.

Palantir
Ah. That's good. I'll give it a go.
Tom Savage
+1  A: 

You could tag the current time value to the file you serve

.../file.rtf?15072010141000

That way you don't have to generate unique names, but you can ensure future requests are not cached.

fencliff
+5  A: 

In addition to the possibility of adding a random GET string to the URL (often the easiest way), it would also be possible to solve this by sending the right headers.

Because you are generating static files, this would require a setting in a .htaccess file. It would have to look like this:

<FilesMatch "\.(rtf)$">
Header set Cache-Control "no-store"
</FilesMatch>
Pekka
But wouldn't that only apply to the current page rather than the RTF the page links to? Correct me if I'm wrong. I often am.
Tom Savage
@Tom aww, you're right, I misunderstood that part!
Pekka
@Tom I changed my answer. Cheers for noticing the error.
Pekka
Seems like the best solution
Tom Savage
A: 

Although the simple solution of using no-cache header as suggested by Pekka will work, you will lose the potential benefit of caching if same file is downloaded several times.

If the RTF file is big and you would like your user to enjoy benefit of caching when the file is actually not changed, you might want to check this answer:

http://stackoverflow.com/questions/1971721/how-to-use-http-cache-headers-with-php/1973016#1973016

Tahir Akhtar