Last active
April 13, 2021 14:30
-
-
Save arturmamedov/18bd4b0761a875dccc34500c948d8f84 to your computer and use it in GitHub Desktop.
Create a entire request cache file and serve it instead of exucete all code each time (also in my CMS i add an webhook/event that open url /cache/clear-all for clear all cache when i update data)
This file contains 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 | |
$url = $_SERVER["REQUEST_URI"]; | |
// clear all cache | |
if ($url == '/cache/clear-all') { | |
array_map('unlink', glob("cache/*.html")); | |
exit('Cache clear successfully!'); | |
} | |
// # format url and create cache filename | |
$url = $url == '/' ? 'home' : $url; // if root its home | |
$url = str_replace('/', '', $url); // remove initial slash | |
$cachefile = 'cache/cached-'.$url.'.html'; | |
$cache_cp_generated = "<!-- Cached copy, generated ".date('H:i:s')." -->\n"; | |
//$cachetime = 18000; // @time4cache: uncomment also "if condition" | |
// Serve from the cache if it is younger than $cachetime | |
if (file_exists($cachefile)) { // && time() - $cachetime < filemtime($cachefile) // @time4cache | |
readfile($cachefile); | |
exit; | |
} | |
ob_start(); // Start the output buffer | |
?> | |
<?php | |
// All your application code goes here | |
// (i'm print also $cache_cp_generated in head tag for know from html source if its a cache copy) | |
?> | |
<?php | |
// Cache the contents to a cache file | |
$cached = fopen($cachefile, 'w'); | |
fwrite($cached, ob_get_contents()); | |
fclose($cached); | |
ob_end_flush(); // Send the output to the browser | |
// improvment for me of this article: https://dzone.com/articles/how-to-create-a-simple-and-efficient-php-cache | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment