file_get_contents没有缓存?

lib*_*ire 2 php caching image file-get-contents

我正在使用file_get_contents()从外部网站加载动态图像.

问题是图像已在远程网站上更新,但我的脚本仍然显示旧图像.我假设服务器在某处缓存图像,但是如何在使用file_get_contents获取文件时强制服务器清除缓存并使用更新的图像?

在我的本地机器上,我必须按CTRL + F5强制刷新图像.

我还尝试在我的脚本中添加无缓存标头,但它不起作用:

    $image = imagecreatefromstring(file_get_contents($path));
    header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date dans le passé
header('Content-type: image/png');
imagepng($image);
exit();
Run Code Online (Sandbox Code Playgroud)

Alm*_* Do 18

您的问题是您正在使用外部资源来加载文件.一旦加载 - 向您的客户端发送一些标题是没有意义的.您的图像加载(并且是来自外部资源的缓存).

但是,解决问题很容易.让你像使用的东西想http://domain.com/path/to/image$path.然后就做:

$image = imagecreatefromstring(file_get_contents($path.'?'.mt_rand()));
Run Code Online (Sandbox Code Playgroud)

- 想法是向GET请求添加一些随机值并防止它被缓存.

  • @ShankarDamodaran想象你的图像路径是`http://domain.com/image.php?id = xxx`.添加另一个`?`会破坏有效的URI.所以盲目串联```在常见情况下并不是一个好主意(至少需要澄清`$ path`格式) (2认同)
  • 我总是觉得使用`time()`更好的做法,因为它比`mt_rand()`便宜. (2认同)