How can the Last-Modified header be utilized in PHP to detect page updates?
The Last-Modified header can be utilized in PHP to detect page updates by storing the last modification time of a page and comparing it with the If-Modified-Since header sent by the browser. If the page has been modified since the last request, the server can send a 200 OK response with the updated content. If the page has not been modified, the server can send a 304 Not Modified response, indicating that the browser can use its cached version.
$lastModifiedTime = filemtime($filePath); // Get the last modification time of the file
$ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
if ($ifModifiedSince && strtotime($ifModifiedSince) >= $lastModifiedTime) {
header('HTTP/1.1 304 Not Modified');
exit;
}
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModifiedTime) . ' GMT');
// Output the content of the page
Related Questions
- What are potential pitfalls to be aware of when using strpos(), substr_count(), or preg_match() to identify specific strings in PHP?
- What are the limitations of PHP in directly calling functions from a DLL or using a Lib file?
- How can the use of extract($_POST) and register_globals impact the functionality of PHP scripts, especially when dealing with input elements?