php

Caching Data to a File Using PHP

Last updated: 21.02.2026
Views: 277

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.

PHP

// Cache lifetime in seconds
$expires = 3600; 
$cache_file = 'data.json';
// Some api url
$url = 'https://jsonplaceholder.typicode.com/posts/1/comments';

if (file_exists($cache_file) && (filemtime($cache_file) > (time() - $expires))) {
	// Getting data from the cache
   	$file = file_get_contents($cache_file);
} else {
	// Write cache
	$file = file_get_contents($url);
	file_put_contents($cache_file, $file, LOCK_EX);
}

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

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

Your email address will not be published. Required fields are marked *