How can HTTP headers be utilized to determine the validity of cached content in PHP?

When serving cached content, it's important to check the HTTP headers to determine if the content is still valid. One common way to do this is by using the "Last-Modified" header, which indicates the last time the content was modified. By comparing this value with the "If-Modified-Since" header sent by the client, we can determine if the cached content is still valid and should be served.

// Check if the cached content is still valid
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($cachedFilePath)) {
    header('HTTP/1.1 304 Not Modified');
    exit;
}

// Serve the cached content
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($cachedFilePath)) . ' GMT');
readfile($cachedFilePath);