PHP data caching

PHP
14.07.19

Sometimes it becomes necessary to limit the number of queries to an external data source. Especially if they do not change constantly. For example, the exchange rate in the central bank. Or simply speed up the page loading, giving the script an already generated file.

$expires = 3600; //Cache lifetime in seconds
$curTime = time(); 
$cacheFile = 'data.json';
 
 
function writeCache($cacheFile)
{
    //get fresh data
    file_put_contents($cacheFile, file_get_contents('http://somesite.com/api'));
 
}
 
if (!file_exists($cacheFile)) {
    writeCache($cacheFile);
} else {
    $fMtime = filemtime($cacheFile);
    if (($curTime - $fMtime) > $expires) {
        writeCache($cacheFile);
    }
}

This caching method is based on comparing the date of the file change with the cache with the current time.

blog comments powered by Disqus