Jump to content

Caching of files in PHP?


random1

Recommended Posts

Hey All,

 

How can you enable the caching of files intelligently? I have a site that has many images (PNGs) that are currently being downloaded again and again for each browser request.

 

How can I set it up so that:

 

1) they download a file that is 300KB in size once

2) the file is cached locally

3) the file is then ONLY downloaded again if the file has changed (different file size)

 

Is there a PHP setting or server setting to get it behaving like this?

 

Previously I have read that there is a way with Apache but it requires changing the file's name each time which I think is a bit ridiculous.

Link to comment
https://forums.phpfreaks.com/topic/136452-caching-of-files-in-php/
Share on other sites

I do this quite regularly to cache background images, and mostly non-changing css and javascript files. First I create a directory in my root called 'static'. Then I create a subdomain - static.domain.com. I point the subdomain at the 'static' folder.

 

I then go through the site and change all references to the static files to static.domain.com/filename.ext

 

Finally, in the static folder, I add an .htaccess file, with the following code inside:

 

<FilesMatch "\.(gif|jpe?g|png|css|js)$">
  
Header set Cache-Control "max-age=29030400, public"
ExpiresDefault "access plus 2 years"

</FilesMatch>

 

What this does is caches the files (gif, jpg, jpeg, png, css, js) for 2 years from the access date. If you change the file, then change the filename. Append a number to the end of it, and increment it each time you change the file. This will force a fresh download of the file in such a case.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.