Skip to content

Instantly share code, notes, and snippets.

@fzyzcjy
Last active July 22, 2018 03:12
Show Gist options
  • Save fzyzcjy/c98c73414cd7cd46ee8388e2868984cf to your computer and use it in GitHub Desktop.
Save fzyzcjy/c98c73414cd7cd46ee8388e2868984cf to your computer and use it in GitHub Desktop.
Cache Control for Laravel Response
<?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