Disable Browser Caching

How to prevent web browser caching for PHP files (scripts)

Prevent Browser Caching for PHP Script

Browser cache is a buffer memory of the web browser in which previously accessed resources such as images or fonts are kept as a copy on the user's local computer. If a resource is later needed again, it can be retrieved from the cache faster than if it had to be downloaded again from the web.

 

While this is very good for static resources, it causes problems for dynamic content. If a PHP file is cached, the same content from the cache is always used instead of loading the new content from the server. You can prevent browser caching by telling the web browser not to cache the PHP file. You can tell the browser about this in the PHP header.

 

To do this, first clear the browser cache so that the new PHP header is loaded.
Otherwise, the old cache settings might still apply if the PHP file is already in the browser cache.

 

PHP Header to Disable Browser-Caching:

// set expires header
header('Expires: Thu, 1 Jan 1970 00:00:00 GMT');

// set cache-control header
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0',false);

// set pragma header
header('Pragma: no-cache');

 

Important:
The PHP "header" function must occur before the first output, so you must not output or send any data to the browser beforehand.

 

Some CMS or server plugins use additional header tags to control caching. In this case, it may be necessary to remove them from the header before settings the header.
This can be done using the PHP function "header_remove".

 

Extended Code to Disable Browser-Caching:

// remove header
header_remove('ETag');
header_remove('Pragma');
header_remove('Cache-Control');
header_remove('Last-Modified');
header_remove('Expires');

// set header
header('Expires: Thu, 1 Jan 1970 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Cache-Control: post-check=0, pre-check=0',false);
header('Pragma: no-cache');

Disclaimer: The information on this page is provided "as is" without warranty of any kind. Further, Arclab Software OHG does not warrant, guarantee, or make any representations regarding the use, or the results of use, in terms of correctness, accuracy, reliability, currentness, or otherwise. See: License Agreement