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.
Similar posts:
-
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...
-
How to Send HTML Form Data to Email Using PHP
Sending a form to email is an important and common way of communicating with a web resource user. Let's write a simple form for sending data to email using the PHP mail()...
-
How to Upload Files to a Server Using PHP
Uploading files to a website is a common task. Consider uploading files to a PHP server using the POST method. This will require a form with the "file" field type and an ...
Leave a Reply