【问题标题】:PHP: file_get_contents() force reading the file from server instead of cachePHP:file_get_contents() 强制从服务器而不是缓存中读取文件
【发布时间】:2017-10-23 13:37:42
【问题描述】:

我正在尝试使用

从 JSON 文件中读取我的常量
$const = file_get_contents('/myfolder/const.json');

问题是这将始终从缓存中读取文件,而不是从我的本地 XAMPP 服务器中读取。在开发阶段,由于编辑,该文件是动态的,每次文件发生更改时,我最终都会清除浏览器缓存。如何始终强制从服务器读取(在开发阶段执行此操作的延迟很好。我将切换到正常的后期部署 - 如何?)?任何帮助表示赞赏。

【问题讨论】:

标签: php


【解决方案1】:

有几个“公认”的解决方案。

首先是给文件添加时间戳,比如

$const = file_get_contents('/myfolder/const.json?'.date("Ymdhis"));

你也可以试试这个

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

我建议添加其中之一,清除缓存,然后尝试运行代码。当我在开始开发之前添加时间戳并重新加载页面时,将时间戳添加到文件对我有用。

【讨论】:

  • 您的解决方案将强制浏览器每次都使缓存无效。
  • 谢谢@thomasw_lrd。
【解决方案2】:

您可以执行以下操作以在每次文件更新时使缓存失效

$filePath = "/myfolder/const.json";
$const = file_get_contents($filePath."?k=".filemtime($filePath));

【讨论】:

    【解决方案3】:

    如果您正在运行像 Apache 或 Nginx 这样的标准网络服务器,最好的办法是发送一个 Cache-Control 标头,就像浏览器所做的那样。

    因此,对于file_get_contents,您需要创建一个上下文资源,例如:

    $context = [
        'http' => [
            'header' => "Cache-Control: no-cache\r\n" .
                "Pragma: no-cache\r\n"
        ]
    ];
    

    最后,请求:

    $file = file_get_contents('/myfolder/const.json', false, $context);
    

    另外,依赖服务器提供的 chroot 可能不是一个好主意。而是通过__DIR__ . /myfolder/const.json 提供文件的绝对路径,这样您就不必处理缓存失效的所有痛苦。或者,使用 http:// . $_SERVER['SERVER_ADDR'] . '/myfolder/const.json 之类的东西会让你再次不得不处理所有缓存 PITA。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2015-02-14
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多