Caching Data to a File Using PHP
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.
Similar posts:
-
Fixing Image URL in ACF (Advanced Custom Fields)
The ACF (Advanced Custom Fields) plugin is a great and convenient tool for extending the functionality of Wordpress. ACF allows you to add custom fields to your project's...
-
How to Remove the jQuery Migrate Script from WordPress
If your WordPress project uses jQuery, then by default, WordPress also loads the jQuery Migrate script along with it. In 99% of cases, you don’t actually need this script...
-
Iterating Elements of Array without Loops
The examples are very abstract because there are cycles. Our condition will be as follows. It is necessary to select all elements of the array by a given attribute. Or, t...
Leave a Reply