Laravel标题和缓存在php中

Laravel标题和缓存在php中,第1张

概述我有一个小图像生成器作为我的laravel4应用程序的一部分.生成图像大约需要700毫秒,因此我已经开始在服务器上缓存生成的结果并将其返回到浏览器,这节省了一些时间. 由于图像在生成后永远不会改变,我想告诉浏览器在本地缓存图像,我使用以下代码完成了此 *** 作: $path = $cacheFolderPath . $cacheFileName;if (File::exists( $path )){ 我有一个小图像生成器作为我的laravel4应用程序的一部分.生成图像大约需要700毫秒,因此我已经开始在服务器上缓存生成的结果并将其返回到浏览器,这节省了一些时间.

由于图像在生成后永远不会改变,我想告诉浏览器在本地缓存图像,我使用以下代码完成了此 *** 作:

$path = $cacheFolderPath . $cachefilename;if (file::exists( $path )){    $response = Response::make(file::get($path));    $response->header('Content-Type','image/png');    $response->header('Content-disposition','inline; filename="'.$cachefilename.'"');    $response->header('Content-transfer-encoding','binary');    $response->header('Cache-Control','public,max-age=10800,pre-check=10800');    $response->header('Pragma','public');    $response->header('Expires',date(DATE_RFC822,strtotime(" 2 day")) );    $response->header('Last-ModifIEd',file::lastModifIEd($path)) );    $response->header('Content-Length',filesize($path));    return $response;}

这会向浏览器发送状态代码为200 OK的图像,并带有以下标题

Cache-Control:max-age=10800,pre-check=10800,publicConnection:Keep-AliveContent-disposition:inline; filename="pIE_0_normal.png"Content-Length:2129Content-transfer-encoding:binaryContent-Type:image/pngDate:Wed,07 Aug 2013 10:29:20 GMTExpires:Fri,09 Aug 13 10:29:20 +0000Keep-Alive:timeout=5,max=93Last-ModifIEd:Wed,07 Aug 13 10:14:42 +0000Pragma:publicServer:Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7Set-cookie:laravel_session=767487mhf6j2btv3k01vu56174; expires=Wed,07-Aug-2013 12:29:20 GMT; path=/; httponlyX-Powered-By:PHP/5.4.7

我的问题是我的浏览器(Chrome,未在其他人中测试过)仍然拒绝简单地获取本地缓存版本,而是再次点击服务器.

我花了大约半个小时寻找关于这个主题的其他问题,所有这些问题都给了我答案,我已将其纳入上述代码中.因此,虽然我知道有类似的问题,但这个问题对于上述源代码是独一无二的.

我的问题是,我做错了什么会导致文件没有被浏览器缓存?

解决方法 另一种方法是检查’If-ModifIEd-Since’请求标头,因为只有在浏览器已有文件时才会出现.

如果它存在,那么您知道该文件已经创建并且可以使用指向它的链接进行响应,否则运行上面的代码.像这样……

// check if the clIEnt valIDating cache and if it is currentif ( isset( $headers['If-ModifIEd-Since'] ) && ( strtotime( $headers['If-ModifIEd-Since'] ) == filemtime( $image->get_full_path() ) ) ) {    // cache IS current,respond 304    header( 'Last-ModifIEd: ' . $image->get_last_modifIEd(),true,304 );} else {    // not cached or clIEnt cache is older than server,respond 200 and output    header( 'Last-ModifIEd: ' . $image->get_last_modifIEd(),200 );    header( 'Content-Length: ' . $image->get_filesize() );    header( 'Cache-Control: max-age=' . $image->get_expires() );    header( 'Expires: '. gmdate('D,d M Y H:i:s \G\M\T',time() + $image->get_expires() ) );    header( 'Content-Type: image/jpeg');    print file_get_contents( $image->get_full_path() ); }
总结

以上是内存溢出为你收集整理的Laravel标题和缓存在php中全部内容,希望文章能够帮你解决Laravel标题和缓存在php中所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1258467.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存