Last Updated: February 25, 2016
· rainphp

PHP Cache with register_shutdown_function()

registershutdownfunction() registers a function for execution on shutdown.

In combination with obstart() and obget_clean() you can access the output before is sent to the user and cache or modify it.


$dir = getcwd() . "/cache/";
$cache = $dir . md5($_SERVER['REQUEST_URI']) . ".html";
if( file_exists($cache) && 
    (time()-filemtime($cache)) < 86400)
    die( file_get_contents($cache) );
function cacheSave( $cache ){
    if ( !error_get_last() )
        file_put_contents($cache, ob_get_flush());
register_shutdown_function('cacheSave', $cache );

Just add the following code at the beginning of the front controller to enable the cache:

require "cache.php";

registershutdownfunction() access the filesystem from the root (/) so to access the files in your web root you have to use the absolute path!

Here is a cache library that implements plugins, caches the HTML and minify CSS, JS