Last active
November 10, 2016 19:51
-
-
Save dhaupin/428f907907763069a249 to your computer and use it in GitHub Desktop.
Function - Cachebuster - Add timestamp to assets in order to break out of browser caching
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 | |
if (!function_exists('addTimestamp')) { | |
function addTimestamp($src, $remote = false, $man_v = '') { | |
if (empty($src)) { | |
return; | |
} elseif ($_SERVER['HTTP_HOST'] === $_SERVER['SERVER_NAME']) { | |
$local_root = $_SERVER['DOCUMENT_ROOT'] . '/'; | |
preg_match('/^([https]+:)?\/\//', $src, $src_proto); | |
$src_proto = (isset($src_proto[0])) ? $src_proto[0] : ''; | |
$local_domain = $src_proto . $_SERVER['SERVER_NAME'] . '/'; | |
$local_file = realpath(str_replace($local_domain, $local_root, $src)); | |
if (file_exists($local_file)) { | |
return $src . '?v=' . date('Ymd.His', filemtime($local_file)) . $man_v; | |
} | |
if ($remote) { | |
$src_rewrite = preg_replace('/^\/\/|^(?!https?:)/', 'https://', $src); | |
$remote_file = get_headers($src_rewrite, 1); | |
if (isset($remote_file['Last-Modified'])) { | |
return $src . '?v=' . date('Ymd.His', strtotime($remote_file['Last-Modified'])) . $man_v; | |
} elseif (isset($remote_file['Etag'])) { | |
return $src . '?v=' . $remote_file['Etag'] . $man_v; | |
} | |
} | |
} | |
return ($man_v) ? $src . '?v=' . $man_v : $src; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment