防止浏览器缓存图像

时间:2016-09-08 18:44:35

标签: php caching laravel-5 meta php-5.6

要实现未经身份验证的用户无法通过猜测URL来查看图像(例如http://www.test.com/images/123.jpg我将所有图像存储在公共目录之外,并提供一个接受该唯一ID的URL图片并检查用户是否经过身份验证:

// Laravel code behind http://www.test.com/image/5
public function getimage($uid) {

    if(Auth::check()) {

        $filename = Picture::findorfail($uid)->filename; // e. g. '123.jpg'
        return response()->download(storage_path('images/' . $filename), null, [], null);

    } else {

        return response()->download('images/no_access.jpg', null, [], null);

    }

}

因此,经过身份验证的用户获取图像“123.jpg”,未经过身份验证的用户获取图像“no_access.jpg”,这只是白色背景上的“无法访问”的红色文本。

一切正常,只要我在退出后手动清除浏览器的缓存(我的情况下是Chrome)。

但是如果

  • 我登录并通过http://www.test.com/image/5访问图片然后我得到图像'123.jpg'(正确到这里)
  • 然后注销并再次调用http://www.test.com/image/5然后我应该得到'no_access.jpg'但是由于浏览器缓存,我得到受保护的图像'123.jpg'(缓存覆盖授权检查)

我已经尝试<meta http-equiv="expires" content="0">但没有成功。 Agian,如果我硬盘清理,一切都很完美 - 但普通用户不会这样做。

如何告诉浏览器不缓存?

提前致谢!

3 个答案:

答案 0 :(得分:2)

尝试将随机变量放在网址的末尾

transpose(stats)

答案 1 :(得分:2)

您可以阻止浏览器缓存图片,但您必须创建.htaccess文件并将以下内容添加到其中:

<filesMatch "\.(jpg|png)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

希望这会有所帮助:)

答案 2 :(得分:0)

有了@CharlotteDunois的想法,我做了一些测试,并发现在Laravel 5.3中,以下内容适用于我的所有用例:

return response()->download(
    storage_path('images/' . $filename),
    null,
    [ 'Cache-Control' => 'no-cache, no-store, must-revalidate', 'Pragma' => 'no-cache', 'Expires' => '0' ],
    null
);

第三个参数表示标题集。注意使用header-name(例如'Cache-Control')作为数组键,并使用header-value(例如'no-cache')作为数组值。互联网上有提议的解决方案说['Cache-Control: no-cache'] ......这是错误的!您必须使用['Cache-Control' => 'no-cache']。祝你好运。

感谢您的所有输入!