php

Caching Data to a File Using PHP

Last updated: 06.04.2026
Views: 365

Sometimes it becomes necessary to limit the number of requests to an external data source, especially when the data does not change frequently. For example, this can be useful when working with APIs that provide exchange rates, weather data, or other information that is updated only periodically. Making a request on every page load in such cases is inefficient and can slow down your application.

A simple and effective solution is to cache the data in a local file. Instead of requesting fresh data each time, the script first checks whether a cached version already exists and whether it is still актуален. This approach can significantly reduce the number of external requests and improve page loading speed.

The basic idea behind file-based caching is to compare the last modification time of the cache file with the current time. If the file is still “fresh” (for example, updated within the last hour), the script uses its contents. Otherwise, it fetches new data from the external source, updates the cache file, and then returns the fresh result.

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 method is easy to implement in PHP and works well for many small to medium projects where a full caching system is not required.

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 *