Home >Backend Development >PHP Tutorial >How Can I Prevent Browser Caching of Assets Served by PHP?

How Can I Prevent Browser Caching of Assets Served by PHP?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 22:29:11542browse

How Can I Prevent Browser Caching of Assets Served by PHP?

Overcoming Browser Caching of Assets Served by PHP Pages

When frequent updates are made to CSS, JS, or image files, browsers often retain the older cached versions, hindering the display of recent changes. This issue can be particularly frustrating for developers who rely on PHP to serve their site pages.

Solution: Disabling Browser Caching

To prevent browser caching of assets retrieved from PHP pages, implement the following code in your PHP scripts:

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");

This code block instructs the browser to:

  • no-store: Do not store the page in the browser's cache.
  • no-cache: Do not use a cached version of the page, even if it is available.
  • must-revalidate: Always revalidate the request with the server before displaying any version of the page.
  • max-age=0: Set the maximum age of the cached version to 0 seconds.
  • post-check=0, pre-check=0: Turn off post-check and pre-check, which are used to determine if the cached version is still valid.
  • Pragma: no-cache: An older directive supported by some browsers.

By incorporating these headers into your PHP scripts, you can effectively disable browser caching and ensure that the most up-to-date versions of your assets are displayed to users.

The above is the detailed content of How Can I Prevent Browser Caching of Assets Served by PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn