Last active
May 3, 2022 02:48
-
-
Save andreescocard/c980584729a3b6685bd6dd2f6817830c to your computer and use it in GitHub Desktop.
PHP simple cache
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
<?php | |
function cache_file() { | |
// something to (hopefully) uniquely identify the resource | |
$cache_key = md5($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING']); | |
$cache_dir = '/tmp/phpcache'; | |
return $cache_dir . '/' . $cache_key; | |
} | |
// if we have a cache file, deliver it | |
if( is_file( $cache_file = cache_file() ) ) { | |
readfile( $cache_file ); | |
exit; | |
} | |
// cache via output buffering, with callback | |
ob_start( 'cache_output' ); | |
// | |
// expensive processing happens here, along with page output. | |
// | |
function cache_output( $content ) { | |
file_put_contents( cache_file(), $content ); | |
return $content; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment