Super Simple PHP File Cache

Tim Williams • November 11, 2015

If you are using a PHP version > 4.3.0 you can use this ultra simple file caching method to cache any kind of dynamic data. If you’re doing API calls or using PHP to pull data from another server it’s always good to implement some kind of caching layer.

$exists = file_exists('something.cache');
if( !$exists || 
    ( $exists && 
      time() > strtotime('+2 hours', filemtime('something.cache'))
    )
) {
    $data = ''; // --> get your dynamic data here...
    // Don't forget to serialize() or json_encode() if the content is not a string!
    file_put_contents('something.cache', $data);
}
else
{
    // --> Don't forget to unserialize() or json_decode() if the data isn't a string!
    $data = file_get_contents('something.cache');
}

This code should be pretty easy to follow! If the file does not exists, or the file was modified more than 2 hours ago, we do something to get fresh data and then generate the new ‘something.cache’ file. If it exists and is less than 2 hours old, we’re good to load that cache!