Disable HTTP Cache With PHP

HTTP Caching can be an important feature for websites it will allow your browser to cache your web elements that your page will collect via HTTP. When HTTP caching is turned on your web pages will load faster and will make sure there is less load on your Web server.

This is able to work because the resources it will cache are resources that will rarely change these are images, css and javascript files. The browser will take these resources and make a local copy of it, so when you revisit the page the browser can just use the local copy and will not have to download the resource again.

To define how long a resource is cached for we use the parameter expires this defines a date after which the resource is invalid. When this date runs out then this will tell the browser they need to get the resource again. If you need the resource to be downloaded more often then make sure you put a lower amount in the expires parameter.

Therefore if you want to disable this HTTP cache feature then all you need to do is make sure that the resource expires immediately.

Use the PHP snippet below to make the resource expiry immediately, place this at the top of your PHP file.

header("Content-Type: application/json");
header("Expires: 0");
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");

If the 0 in the header expires isn't working on expires due to old browsers not understanding it, you can try putting the date to a time in the past.

header("Content-Type: application/json");
header("Expires: on, 01 Jan 1970 00:00:00 GMT");
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");

Advertise here 50% Off

Comment