-1

I've found plenty of information about how to stop caching, but very little on forcing caching. I have a dynamic PHP page which retrieves data from the database. On this page, I have a button which uses a JS function to reload the page and update the content if the user clicks it. The page also redirects after a certain period of time.

  • After page has redirected if user presses back button in browser, show them same page that was present before the redirect.

Is this possible with PHP only using header cache-control?

Right now, I'm using header("Cache-Control: max-age=3600, private"); which doesn't cache the page at all.

EternalHour
  • 8,308
  • 6
  • 38
  • 57
  • Possible duplicate of [PHP: Detect Page Refresh](http://stackoverflow.com/questions/4290230/php-detect-page-refresh) – Gavriel Jan 29 '16 at 02:29
  • Not all browsers do this, but a fairly reliable way would be to check if the `$_SERVER['HTTP_REFERER']` is empty. – Iwnnay Jan 29 '16 at 02:29
  • To whoever marked this as a duplicate, this question is about caching. It is not a duplicate of that question. – EternalHour Jan 29 '16 at 02:52

1 Answers1

0

In order to solve this issue, you have to consider several things.

First of all, for dynamic content the page where you need to set the headers may not necessarily be the page you think. Here's an example.

Say you have a PHP script, which includes another PHP script. The included page is what you and the user sees, however, as far as the browser is concerned the request came from that parent PHP file. In my case, I was trying to set the headers in included.php, rather than parent.php.

The second consideration is if you are using sessions. If you need to cache the session data as well as the page content, you will need to use session_cache_limiter() to set the correct headers before you start the session on that page.

My issues became apparent when I used the browser developer tools to see the network request and looked through the headers. Even though I was setting them and specifying an expiration (max-age), the browser ignored it.

enter image description here

But, even after setting the correct cache-control headers, and seeing them in the developer tools the page still was not being cached. How could this be!?! I'll tell you why, notice that Pragma: "no-cache" in those headers? That's why! We need to change it.

header("Cache-Control: max-age=5600, private_no_expire");
header("Pragma: cache");

require_once 'included.php';

enter image description here

That looks better. Now with any luck, your page will be caching.

EternalHour
  • 8,308
  • 6
  • 38
  • 57