In web development, sometimes we need to make sure that the browser or proxy server does not cache our pages so that users can get the latest content every time they visit. The header() function provided by PHP can be used to send HTTP headers to control cache behavior. This article will introduce in detail how to set Cache-Control and Pragma using the header() function to effectively prevent caching.
Browser cache is designed to improve performance and reduce server pressure, but in some scenarios (such as: dynamic data, user personal information, sensitive operation pages, etc.), we need to force the browser to get the latest content from the server every time, rather than loading it from the cache.
If cache control is not set correctly, users may see expired pages, resulting in inconsistent data or errors in operation.
PHP's header() function allows you to send raw HTTP header information to the browser, which must be called before any output (echo, print, HTML).
Cache-Control is an important header introduced by HTTP/1.1 and is used to define caching policies. To disable caching, you can use the following command:
no-store : No cache is allowed.
no-cache : Must be reverified every time.
Must-revalidate : The expired resource must be confirmed to the server.
Sample code:
<?php
// Disable cache
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
?>
The second header() call here, the false parameter means that the previous header with the same name should not be overwritten, but appended.
Pragma is an old method in HTTP/1.0 for compatibility with old proxy servers.
Sample code:
<?php
header("Pragma: no-cache");
?>
Although Cache-Control is mainly used now, it is recommended to add Pragma: no-cache as well for compatibility.
In addition to Cache-Control and Pragma , you can also set the Expires header, set the expiration time to a certain point in the past, and force the content to expire.
Sample code:
<?php
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
?>
Here is a complete anti-cache example:
<?php
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
// Assume that dynamic content is output
echo "<html><body>";
echo "<h1>Current time: " . date('Y-m-d H:i:s') . "</h1>";
echo "<p>access <a href=\"https://m66.net/demo\">m66.net Sample page</a></p>";
echo "</body></html>";
?>
Header() must be called before sending any output, otherwise a "headers already sent" error will be thrown.
Different browsers and proxy servers have slightly different support for cache instructions. For insurance, it is best to set up Cache-Control , Pragma and Expires at the same time.
If you use a cache plug-in or CDN, you may also need to configure an anti-cache policy at these levels.