Laravel Headers and Caching in php -
i have small image generator part of laravel4 application. takes 700ms generate image , have started caching generated result on server , returning browser instead saves time.
as image never change once generated wanted tell browser cache image locally , have done following code:
$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', date(date_rfc822, file::lastmodified($path)) ); $response->header('content-length', filesize($path)); return $response; }
this sends image status code 200 ok
browser following headers:
cache-control:max-age=10800, pre-check=10800, public connection:keep-alive content-disposition:inline; filename="pie_0_normal.png" content-length:2129 content-transfer-encoding:binary content-type:image/png date:wed, 07 aug 2013 10:29:20 gmt expires:fri, 09 aug 13 10:29:20 +0000 keep-alive:timeout=5, max=93 last-modified:wed, 07 aug 13 10:14:42 +0000 pragma:public server:apache/2.4.3 (win32) openssl/1.0.1c php/5.4.7 set-cookie:laravel_session=767487mhf6j2btv3k01vu56174; expires=wed, 07-aug-2013 12:29:20 gmt; path=/; httponly x-powered-by:php/5.4.7
my issue browser (chrome, not tested in others) still refuses grab local cached version , instead hits server again.
i have spent half hour searching other questions on subject , of them have given me answers have incorporated above code. while know there similar questions, 1 unique above source code.
my question is, doing wrong result in file not being cached browser?
an alternative method check 'if-modified-since' request header present if browser has file.
if present, know file created , can respond link it, otherwise run code above. this...
// check if client validating cache , if current if ( isset( $headers['if-modified-since'] ) && ( strtotime( $headers['if-modified-since'] ) == filemtime( $image->get_full_path() ) ) ) { // cache current, respond 304 header( 'last-modified: ' . $image->get_last_modified(), true, 304 ); } else { // not cached or client cache older server, respond 200 , output header( 'last-modified: ' . $image->get_last_modified(), true, 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() ); }
Comments
Post a Comment