Skip to content

Instantly share code, notes, and snippets.

@andreescocard
Last active May 3, 2022 02:48
Show Gist options
  • Save andreescocard/c980584729a3b6685bd6dd2f6817830c to your computer and use it in GitHub Desktop.
Save andreescocard/c980584729a3b6685bd6dd2f6817830c to your computer and use it in GitHub Desktop.
PHP simple cache
<?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