Skip to content

Instantly share code, notes, and snippets.

@mxmaxime
Last active November 9, 2017 15:34
Show Gist options
  • Save mxmaxime/b6e04f5980478f51d1df7dcc088def66 to your computer and use it in GitHub Desktop.
Save mxmaxime/b6e04f5980478f51d1df7dcc088def66 to your computer and use it in GitHub Desktop.
<?php
/**
* Not Modified field based
* Warning: if you change the file and the field
* `updatedAt` don't change, your users won't see the change
* (except those who don't have a cache)
*/
$result = [
'title' => 'Hello world',
'content' => 'lorem lorem lorem lorem',
'updatedAt' => 1510235856 // = time()
];
$lastModifiedTime = $result['updatedAt'];
// Generate etag from the last modified date.
$etag = 'W/"' . md5($lastModifiedTime) . '"';
// Generate gmd date
$gmdate = gmdate('D, d M Y H:i:s', $lastModifiedTime);
// Set headers (for response)
header('Last-Modified: ' . $gmdate . " GMT");
// If you want to fix a maximum lifetime
header('Cache-Control: public, max-age=604800');
header("Etag: $etag");
/**
* Check request headers
*/
$ifModifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? null;
$ifNoneMatch = $_SERVER['HTTP_IF_NONE_MATCH'] ?? null;
if (
($ifModifiedSince !== null && strtotime($ifModifiedSince) === $lastModifiedTime) ||
($ifNoneMatch !== null && $etag === trim($ifNoneMatch))
) {
// Okay browser, use your version from the cache.
header('HTTP/1.1 304 Not Modified');
exit();
}
sleep(2);
header("Content-type: application/json; charset=UTF-8");
echo json_encode($result);
<?php
/**
* Not Modified file based
* If the php file change, the cache is invalided.
*/
// Current file
$file = __FILE__;
$lastModifiedTime = filemtime($file);
// Generate etag from the last modified date.
$etag = 'W/"' . md5($lastModifiedTime) . '"';
// Generate gmd date
$gmdate = gmdate('D, d M Y H:i:s', $lastModifiedTime);
// Set headers (for response)
header('Last-Modified: ' . $gmdate . " GMT");
// If you want to fix a maximum lifetime
header('Cache-Control: public, max-age=604800');
header("Etag: $etag");
/**
* Check request headers
*/
$ifModifiedSince = $_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? null;
$ifNoneMatch = $_SERVER['HTTP_IF_NONE_MATCH'] ?? null;
if (
($ifModifiedSince !== null && strtotime($ifModifiedSince) === $lastModifiedTime) ||
($ifNoneMatch !== null && $etag === trim($ifNoneMatch))
) {
// Okay browser, use your version from the cache.
header('HTTP/1.1 304 Not Modified');
exit();
}
// Fake long response...
sleep(2);
echo "<h1>Hello world </h1>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment