PHP data caching


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(''));
if (!file_exists($cacheFile)) {
} else {
    $fMtime = filemtime($cacheFile);
    if (($curTime - $fMtime) > $expires) {

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