Last active
February 6, 2025 10:23
-
-
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
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, thanks & thanks again for this piece of code. Everything is clear for me now ^^