Created
July 29, 2013 15:43
-
-
Save openprojdev/6105277 to your computer and use it in GitHub Desktop.
Auto versioning of static file based on unix mtime
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 | |
/* | |
* .htaccess | |
* <IfModule mod_rewrite.c> | |
* RewriteEngine on | |
* RewriteCond %{REQUEST_FILENAME} !-d | |
* RewriteCond %{REQUEST_FILENAME} !-f | |
* RewriteRule ^(.*)\.(.+)\.(css|js)$ $1.$3 [L] # Strip out the version number | |
* </IfModule> | |
* | |
*/ | |
/* | |
* timestamp to base64 shortner | |
*/ | |
function shorten($id, $alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-') | |
{ | |
$base = strlen($alphabet); | |
$short = ''; | |
while($id) { | |
$id = ($id-($r=$id%$base))/$base; | |
$short = $alphabet{$r} . $short; | |
}; | |
return $short; | |
} | |
/** | |
* Given a file, i.e. /css/base.css, replaces it with a string containing the | |
* file's mtime, i.e. /css/base.1221534296.css. | |
* | |
* @param $file The file to be loaded. Must be an absolute path (i.e. | |
* starting with slash). | |
*/ | |
function auto_version($file) | |
{ | |
if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) | |
return $file; | |
$mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); | |
$short = shorten($mtime); | |
return preg_replace('{\\.([^./]+)$}', ".$short.\$1", $file); | |
} | |
//this function should be called where ever we include the static files, like in common header.php | |
echo auto_version('/js/jquery.js'); | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment