58

How to clear browser cache with php?

ZA.
  • 8,839
  • 10
  • 34
  • 39
  • 8
    You mean: How to prevent my stuff from being cached. You can´t *clear* a browsers cache from the server without preinstalled software (activeX etc.) that has extensive rights to modify the user´s system. – anddoutoi Jun 24 '09 at 09:25

4 Answers4

56
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-Type: application/xml; charset=utf-8");
ZA.
  • 8,839
  • 10
  • 34
  • 39
37

You can delete the browser cache by setting these headers:

<?php
header("Expires: Tue, 01 Jan 2000 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, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
robert
  • 1,163
  • 10
  • 19
user1032289
  • 464
  • 5
  • 12
  • This works for me. I tried to make a preview of a 6MB pdf. My script working for small sized pdfs but not more than 3 mbs. – user2439124 May 29 '18 at 11:06
  • This is the way how to clear cache including loaded audio or image file path. – Rowf Abd Aug 20 '18 at 20:14
  • 2
    This won't clear a cache that's already there. If the browser has visited the page previously and the headers were set to cache, it will most likely just load the cached files and never receive the new no-cache headers until the user manually refreshes the content on their end. – Peter Cullen Dec 13 '18 at 01:07
2

It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.

You can do it by subfolders (example /css/v1/style.css) or by filename (example: css/style_v1.css) or even by setting different folders for your website, example:

www.mywebsite.com/site1

www.mywebsite.com/site2

www.mywebsite.com/site3

And use a .htaccess or even change httpd.conf to redirect to your current application.

If's about one image or page:

    <?$time = date("H:i:s");?>
    <img src="myfile.jpg?time=<?$time;?>">

You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.

Marcelo Agimóvel
  • 1,432
  • 2
  • 14
  • 23
1

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

nadavkav
  • 426
  • 7
  • 9