Example
<?php
function remember(string $key, int $ttl, callable $callback): mixed
{
$directory = '/home/account/private-cache';
$safeKey = hash('sha256', $key);
$path = $directory . '/' . $safeKey . '.json';
if (is_file($path) && filemtime($path) >= time() - $ttl) {
$cached = json_decode((string) file_get_contents($path), true);
if (json_last_error() === JSON_ERROR_NONE) {
return $cached;
}
}
$value = $callback();
$json = json_encode($value, JSON_THROW_ON_ERROR);
file_put_contents($path, $json, LOCK_EX);
return $value;
}
$data = remember('homepage-stats', 300, function () use ($pdo) {
return $pdo->query(
'SELECT COUNT(*) AS total FROM articles'
)->fetch();
});
Notes
Create the cache directory with restrictive permissions and keep it outside the public web root. For multi-server applications or high concurrency, use a shared cache such as Redis. Validate cache keys and define a cleanup policy.