diff --git a/src/Http/Request.php b/src/Http/Request.php index 03843a5..3c860d0 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -20,6 +20,16 @@ public static function setRequestPayload(RequestPayload $requestPayload): void{ self::$lastProcessedRequestPayload = $requestPayload; } + public static function getFirstHeaderValue(string $headerName): ?string{ + foreach(getallheaders() as $name => $value){ + if (strtolower($name) === strtolower($headerName)){ + return $value; + } + } + + return null; + } + /** * Fetches the raw body of a request */ diff --git a/src/Router/Router.php b/src/Router/Router.php index 6e66fc0..ec522a8 100644 --- a/src/Router/Router.php +++ b/src/Router/Router.php @@ -1,10 +1,12 @@ noxInstance->staticFileHandler->getCacheTimeForMime($mimeType); if ($cacheTime !== null) { + header(sprintf("cache-control: max-age=%d", $cacheTime)); + + $lastModifiedTime = filemtime($staticFilePath); + if ($lastModifiedTime !== false){ + $lastModifiedDateTime = new DateTime('UTC'); + $lastModifiedDateTimestamp = $lastModifiedDateTime->format('D, d M Y H:i:s \G\M\T'); + header(sprintf("last-modified: %s", $lastModifiedDateTimestamp)); + header(sprintf("etag: %d", $lastModifiedTime)); + + // Check if the client sent an "If-None-Match" header with the same etag used above + // If so, simply respond with 304 Not Modified and exit. + // Else, don't exit + $ifNoneMatch = Request::getFirstHeaderValue("If-None-Match"); + if ((string) $lastModifiedTime === $ifNoneMatch){ + // Etags match, no need to send file. It's not stale + http_response_code(304); + exit(); + } + } } $fileContents = file_get_contents(realpath($staticFilePath));