Dec
10
PHP - Prevent Browser And Proxy Cache
December 10, 2007 |
One thing that had been always troubling me was the proxy cache. There are many processes server data needs to go through before it appears on our screen. If you use Yahoo! Web Hosting or BlueHost in Asia, you may find that after you upload a new web page to the remote hosting server, it takes a long time to see any real changes. Many people blame the hosting company on this, actually this is caused by the proxy the web page goes through, not the server’s problem.
A server can explicitly inform the browser, and any proxy caches that might be between the server and browser, of a specific date and time for the document to expire. Proxy and browser caches can hold the document until that time or expire it earlier. Repeated reloads of a cached document do not contact the server. However, an attempt to fetch an expired document does contact the server.
So no matter what you do (rewrite the file a million times through ftp or clear all your cache), you won’t get the new updated page displayed, because the proxy in the middle of the server and your browser does the ‘evil’ caching. Caching can make web developers frustrated, but once you know how it works and control it, it’s not that evil at all.
About how it works, which is a long story, has been brilliantly told by The World Wide Web Consortium (W3C) - HTTP. But that’s a long story as I said, and you need to read for days to get the piece of information you need. Finally, I found a quick and dirty version of it - simple and plain code. Below is the best way to prevent a browser or proxy cache from storing your HTML document:
<?php
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");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title></title>
</head>
<body>
</body>
</html>
The only catch to setting headers is that you must do so before any of the body is generated. This means that all calls to header( ) (or setcookie( ), if you’re setting cookies) must happen at the very top of your file, even before the tag.
Although the code above works fine, I still think it’s a good idea to understand how HTTP works.
Similar Posts
- None Found


































