0
votes

Many PHP developers add the no-cache header on top of their PHP pages, so do I, for obvious reasons. Since PHP generated content is usually dynamic, having the browser cache them results in outdated data being presented to the user. To avoid this caching is usually disabled.

<?php
    //no  cache headers 
    header("Expires: Mon, 26 Jul 1990 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
?>

The problem is that due to this header, also my images, javascript files and css files, which are static and thus could (and should) be cached, are also not being cached. This slows down the site a lot.

Is there a way to have no cache on the PHP content, but still have cached js/images/css?

How can this be achieved, assuming I have full access to modify the (linux) server config, HTACCESS and of course, the PHP files themselves?

Or is the whole "no-cache thing" unnecessary for dynamic PHP files? Even when they are url-rewritten to appear extension-less.

2
Already you have header("Expires: Mon, 26 Jul 1990 05:00:00 GMT"); right?Praveen Kumar Purushothaman
Yes, as I posted, why?Gilles Lesire
Sorry I got confused. Don't mind my comment!Praveen Kumar Purushothaman

2 Answers

2
votes

I Might be wrong but I beleive you can bring all your js and CSS files into a single php and then cache that using something like

ob_start ("ob_gzhandler");
ob_start("compress");

So you would have a .php the defines its header then a few requires on your js and css file's and also the above.

You will probobly need a couple of if statements to pickup changes etc.

I will make a more comprehensive answer in a few I am on my phone at the moment.


UPDATE

Found a resource on git that I think will help set you in the right path.

https://github.com/SubZane/CSS-Compressor/blob/master/csscompressor.php

1
votes

you can use a htaccess to define files that you want to be cached all you want is to make a .htaccess file in the main directory of your website and add this code

example:

# cache images/pdf docs for 1 week
<FilesMatch "\.(ico|pdf|jpg|jpeg|png|gif)$">
  Header set Cache-Control "max-age=604800, public, must-revalidate"
  Header unset Last-Modified
</FilesMatch>

# cache html/htm/xml/txt diles for 2 days
<FilesMatch "\.(css|js)$">
  Header set Cache-Control "max-age=172800, must-revalidate"
</FilesMatch>