croceldon
croceldon

Reputation: 4615

How to force page not to be cached in PHP?

I have a page, index.php, that shows information based on a mysql db. There are forms on it, and the action for the forms is set to a separate page called process.php. Process.php does all the database CRUD stuff, then uses

header("Location: /webadmin/email/index.php");

to send the user back to the original page.

This seems to be working fine, except for the fact that the original index page doesn't always reflect the changes made by process.php. I assume that the page is being cached, because if I do a refresh (Ctrl + F5), the page will show the latest data.

How can I prevent this page from being cached? I have tried what the PHP page for header() says, but it doesn't seem to work. The Cache-Control and Expires options seem to have no effect at all - the page is still being cached.

Update

Ok, I was partially wrong. Apparently, the following does work in IE:

<?php header("Cache-Control: no-cache, must-revalidate");

However, it is definitely NOT working in FF, which is still showing a cached version. Any ideas on why this is, and how I can make it stop caching?

Upvotes: 20

Views: 45677

Answers (6)

Belldandu
Belldandu

Reputation: 2392

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

do this and it should prevent caching in all browsers

tested in IE FF and chrome

Upvotes: 0

moderns
moderns

Reputation: 650

This is the correct order to get it working on all browsers:

<?php
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Pragma: no-cache"); // HTTP/1.0
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
?>

Upvotes: 13

danii
danii

Reputation: 5703

I would play safely and try to output all cache killers known to man (and browser). My list currently consists of:

<?php
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); // HTTP/1.0
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
?>

Upvotes: 48

Derek Illchuk
Derek Illchuk

Reputation: 5658

Make all browsers fall in line:

header("Location: /webadmin/email/index.php?r=".mt_rand(0, 9999999));

It's not pretty, but it fits the question asked: "How to force..."

Upvotes: 16

graphicdivine
graphicdivine

Reputation: 11221

Try fooling the browser with a spurious querystring:

header("Location: /webadmin/email/index.php?x=1");

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382861

<?php header("Cache-Control: no-cache, must-revalidate");

Upvotes: 8

Related Questions