Php: Create Your Caching System Easily and Quickly

Php: Create your Caching System Easily and Quickly
by Luigi Nori Date: 12-11-2015 php cache

If you need to integrate a caching system quickly, you can use this ultra simple file caching method to cache any kind of dynamic data. Usually, 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);
    // --> Don't forget to unserialize() or json_decode() if the data isn't a string!
    $data = file_get_contents('something.cache');


This code is almost 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!

by Luigi Nori Date: 12-11-2015 php cache hits : 2065  

Related Posts