How can one ensure the validity and timeliness of cached HTML files generated through output buffering in PHP, especially in a scenario where content updates are infrequent?
When using output buffering in PHP to cache HTML files, one can ensure validity and timeliness by implementing a mechanism to check the last modified timestamp of the cached file against the last modified timestamp of the source content file. This way, if the source content has been updated since the cached file was generated, the cached file can be regenerated to reflect the latest changes.
<?php
$source_file = 'source_content.php';
$cached_file = 'cached_content.html';
$cache_duration = 3600; // Cache duration in seconds (1 hour)
if (file_exists($cached_file) && (time() - filemtime($cached_file) < $cache_duration)) {
// Serve cached file
readfile($cached_file);
} else {
ob_start();
include $source_file;
$content = ob_get_clean();
file_put_contents($cached_file, $content);
echo $content;
}
?>
Keywords
Related Questions
- In what scenarios should relative paths be avoided when using require in PHP for variable assignment?
- How can PHP be used to read and determine file types based on their Hex code?
- How can developers effectively troubleshoot issues with transferring data between variables in PHP, and what debugging techniques are recommended for such scenarios?