Skip to content

Instantly share code, notes, and snippets.

@oliworx
Last active July 27, 2022 12:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliworx/4951478 to your computer and use it in GitHub Desktop.
Save oliworx/4951478 to your computer and use it in GitHub Desktop.
Browser caching with Etag and PHP: this saves bandwith and speeds up the loading for the visitor, very useful for mobile pages
ob_start(); // collect all outputs in a buffer
/*
put the normal PHP-Code here
if the resulting html code ($sContent) is the same, and so the md5 hash is the same,
it will not be sent so the client once more
because the client already has this html page in the cache, identified by the md5 hash Etag
*/
$sContent = ob_get_contents(); // collect all outputs in a variable
ob_clean();
$sEtag=md5($sContent); // calculate a hash for the content
if ($_SERVER['HTTP_IF_NONE_MATCH'] == $sEtag) { //browser already requested this page ?
// Okay, the browser already has the
// latest version of our page in his
// cache. So just tell him that
// the page was not modified and DON'T
// send the content -> this saves bandwith and
// speeds up the loading for the visitor
header('HTTP/1.1 304 Not Modified');
header_remove("Cache-Control");
header_remove("Pragma");
header_remove("Expires");
} else {
header('Etag: "'.$sEtag.'"'); // send a ETag with the response
header_remove("Cache-Control"); //let the browser cache the content
header_remove("Pragma");
header_remove("Expires");
echo $sContent;
}
@PBC43
Copy link

PBC43 commented Feb 12, 2022

Thanks, thanks & thanks again for this piece of code. Everything is clear for me now ^^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment