Last active
July 22, 2018 03:12
-
-
Save fzyzcjy/c98c73414cd7cd46ee8388e2868984cf to your computer and use it in GitHub Desktop.
Cache Control for Laravel Response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function addResponseHeaders($request, $response, $ext, $modifiedTimestamp, $downloadFileName = null) | |
{ | |
$mime = ExtToMIME::convert($ext); | |
$headers = &$response->headers; | |
$headers->set('Content-Type', $mime, true); | |
$headers->set('Cache-Control', 'public', true); // TODO max-age=xxx | |
$headers->set('Last-Modified', gmdate("D, d M Y H:i:s", $modifiedTimestamp) . " GMT", true); | |
if ($downloadFileName != null) { | |
$headers->set('Content-Disposition', 'filename="' . $downloadFileName . '"', true); | |
} | |
// note that it should be STRING | |
$eTag = (string) $modifiedTimestamp; | |
addRespETag($request, $response, $eTag); | |
} | |
function addRespETag($request, $response, string $eTag) | |
{ | |
$requestEtag = str_replace('"', '', $request->getETags()); | |
// Check to see if Etag has changed | |
// strpos -> in case the browser gets `{etag}-gzip` | |
if ($requestEtag && strpos($requestEtag[0], $eTag) === 0) { | |
$response->setNotModified(); | |
} | |
// Set Etag | |
$response->setEtag($eTag); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment