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
- What are some potential pitfalls of using the mysql_* functions in PHP, and why should developers consider switching to PDO?
- What are the best practices for handling sessions in PHP, especially when using URLs?
- What potential pitfalls should be considered when defining and accessing array elements in PHP functions handling SQL results?