Skip to content

Instantly share code, notes, and snippets.

@dtbaker
Last active August 29, 2015 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dtbaker/605772152cfaba9ce220 to your computer and use it in GitHub Desktop.
Save dtbaker/605772152cfaba9ce220 to your computer and use it in GitHub Desktop.
Hacky caching with PHP
$key = $_SERVER['REMOTE_ADDR'] . serialize($_REQUEST);
if(strlen($key) < 500){ // help prevent flooding.
$key = md5($key);
// global so we can find it in the shutdown function
$GLOBALS['wordpress_temp_file'] = dirname(__FILE__).'/cache/wp_'.basename($key);
if(is_file($GLOBALS['wordpress_temp_file']) && filemtime($GLOBALS['wordpress_temp_file']) > (time() - 3600)){
$data = unserialize(file_get_contents($GLOBALS['wordpress_temp_file']));
echo $data['content'];
exit;
}
ob_start();
function wordpress_shutdown() {
$data = array(
'request' => $_REQUEST,
'content' => ob_get_clean(),
);
if(isset($GLOBALS['wordpress_temp_file'])) {
file_put_contents( $GLOBALS['wordpress_temp_file'], serialize( $data ) );
}
echo $data['content'];
}
register_shutdown_function('wordpress_shutdown');
}
// run your resource intensive stuff here...
echo "Hello!";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment