Php: Create your Caching System Easily and Quickly

Php: Create your Caching System Easily and Quickly


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!


tags: php cache

We use our own cookies and third-party cookies to improve our services, show products based on your preferences, analyse the browsing habits of our users, and enable interaction with social networks. Continuing to browse our sites implies full acceptance of their use. You can change your cookie setting or get more information here: Cookies policy .