如何防止浏览器缓存PHP页面调用的资源?

问题描述 投票:0回答:7

每当我更新 CSS、JS 或图像文件时,浏览器都会加载存储在缓存中的相同旧文件。我怎样才能防止这种情况发生?我正在使用 PHP 提供我的网站页面。

php browser-cache cache-control
7个回答
358
投票

试试这个

<?php

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

46
投票

这里,如果你想通过HTML来控制它:如下所示选项1:

<meta http-equiv="expires" content="Sun, 01 Jan 2014 00:00:00 GMT"/>
<meta http-equiv="pragma" content="no-cache" />

如果你想通过 PHP 来控制它:像下面这样做选项 2:

header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');

选项 2 总是更好,以避免基于代理的缓存问题。


14
投票

你可以试试这个:

    header("Expires: Tue, 03 Jul 2001 06: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");
    header("Connection: close");

希望它能帮助防止缓存(如果有的话)!


10
投票

我在缓存 css 文件时遇到问题。在 PHP 中设置标题对我没有帮助(也许是因为标题需要在样式表文件中设置,而不是在链接到它的页面中设置?)。

我在此页面找到了解决方案:https://css-tricks.com/can-we-prevent-css-caching/

解决方案:

附加时间戳作为链接文件的 URI 的查询部分。
(可用于css、js、图像等)

开发:

<link rel="stylesheet" href="style.css?<?php echo date('Y-m-d_H:i:s'); ?>">

对于生产(其中缓存主要是一件好事):

<link rel="stylesheet" type="text/css" href="style.css?version=3.2">

(并在需要时手动重写)

或这两者的组合:

<?php
    define( "DEBUGGING", true ); // or false in production enviroment
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo (DEBUGGING) ? date('_Y-m-d_H:i:s') : ""; ?>">

编辑:

或者这两者的更漂亮的组合:

<?php
    // Init
    define( "DEBUGGING", true ); // or false in production enviroment
    // Functions
    function get_cache_prevent_string( $always = false ) {
        return (DEBUGGING || $always) ? date('_Y-m-d_H:i:s') : "";
    }
?>
<!-- ... -->
<link rel="stylesheet" type="text/css" href="style.css?version=3.2<?php echo get_cache_prevent_string(); ?>">

6
投票

根据具体情况,防止浏览器缓存不是一个好主意。 寻找解决方案我发现了这样的解决方案:

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">

这里的问题是,如果在服务器上更新期间文件被覆盖(这是我的场景),则缓存将被忽略,因为即使文件的内容相同,时间戳也会被修改。

我使用此解决方案强制浏览器仅在其内容被修改时才下载资源:

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">

1
投票

您还可以对缓存文件使用查询字符串。它不会影响您的样式或 js 文件的行为。

例如:

example.com/mystyle.css -> 
example.com/mystyle.css?<?php echo random(1000, 5000); ?>

0
投票

如果您无法使用 php 进行更改,可以通过 .htaccess 文件进行更改。

<IfModule mod_headers.c>
    Header set Cache-Control "no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires 0 
</IfModule>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.