Created
March 12, 2019 08:59
-
-
Save Langmans/69579969a6a537a9db980ea37226dca8 to your computer and use it in GitHub Desktop.
easy mode php last-modified/etag headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class HttpCache { | |
/** | |
* @param int $lastModifiedTimestamp | |
* @param int $maxAge | |
* | |
* @return void | |
*/ | |
public static function Init( $lastModifiedTimestamp, $maxAge = null ) { | |
if ( static::IsModifiedSince( $lastModifiedTimestamp ) ) { | |
static::SetLastModifiedHeader( $lastModifiedTimestamp, $maxAge ); | |
} else { | |
static::SetNotModifiedHeader( $maxAge ); | |
} | |
} | |
/** | |
* @param string $file | |
* @param int $maxAge | |
* | |
* @return bool | |
*/ | |
public static function InitFile( $file, $maxAge = null ) { | |
if ( is_file( $file ) ) { | |
$timestamp = max( filemtime( $file ), filemtime( __FILE__ ) ); | |
static::Init( $timestamp, $maxAge ); | |
return true; | |
} | |
static::SetNotFound(); | |
return false; | |
} | |
/** | |
* @param int $lastModifiedTimestamp | |
* | |
* @return bool | |
*/ | |
public static function IsModifiedSince( $lastModifiedTimestamp ) { | |
$allHeaders = getallheaders(); | |
if ( array_key_exists( 'If-Modified-Since', $allHeaders ) ) { | |
$gmtSinceDate = $allHeaders['If-Modified-Since']; | |
$sinceTimestamp = strtotime( $gmtSinceDate ); | |
// Can the browser get it from the cache? | |
if ( $sinceTimestamp !== false && $lastModifiedTimestamp <= $sinceTimestamp ) { | |
return false; | |
} | |
} | |
return true; | |
} | |
/** | |
* @param int $maxAge | |
* | |
* @return void | |
*/ | |
public static function SetNotModifiedHeader( $maxAge = null ) { | |
// Set headers | |
header( 'HTTP/1.1 304 Not Modified' ); | |
if ( $maxAge !== null ) { | |
header( "Cache-Control: public, max-age=$maxAge" ); | |
} | |
die(); | |
} | |
/** | |
* @param int $lastModifiedTimestamp | |
* @param int $maxAge | |
*/ | |
public static function SetLastModifiedHeader( $lastModifiedTimestamp, $maxAge = null ) { | |
// Fetching the last modified time of the XML file | |
$date = gmdate( 'D, j M Y H:i:s', $lastModifiedTimestamp ) . ' GMT'; | |
// Set headers | |
header( 'HTTP/1.1 200 OK' ); | |
if ( $maxAge !== null ) { | |
header( "Cache-Control: public, max-age=$maxAge" ); | |
} | |
header( "Last-Modified: $date" ); | |
} | |
public static function SetNotFound() { | |
header( 'HTTP/1.1 4004 Not Found' ); | |
} | |
public static function SendDoNotCache() { | |
header( 'Cache-Control: no-cache, no-store, must-revalidate' ); | |
header( 'Expires: Thu, 01 Jan 1970 00:00:00 GMT' ); | |
header( 'Pragma: no-cache' ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment