Last active
August 29, 2015 14:09
-
-
Save dtbaker/605772152cfaba9ce220 to your computer and use it in GitHub Desktop.
Hacky caching with PHP
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
$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