Skip to content

Instantly share code, notes, and snippets.

@iamrobert
Forked from Darep/.htaccess
Created April 23, 2024 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamrobert/cfd9fd55a1b53dd1983d8c8dc3d929be to your computer and use it in GitHub Desktop.
Save iamrobert/cfd9fd55a1b53dd1983d8c8dc3d929be to your computer and use it in GitHub Desktop.
PHP CSS&JS auto-versioning function.
# CSS/JS auto-versioning
RewriteEngine On
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
<?php
/**
* 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 string $file The file to be loaded. Must be an absolute path (i.e.
* starts with slash).
* @return string
*/
function auto_version($file) {
$file = str_replace('http://', '', $file);
$file = str_replace('https://', '', $file);
$file = str_replace($_SERVER['SERVER_NAME'], '', $file);
$full_file = $_SERVER['DOCUMENT_ROOT'] . $file;
if (strpos($file, '/') !== 0 || !file_exists($full_file)) {
$full_file = substr($_SERVER['SCRIPT_FILENAME'], 0, -strlen($_SERVER['SCRIPT_NAME']));
$full_file .= $file;
if (!file_exists($full_file)) {
return $file;
}
}
$mtime = filemtime($full_file);
$new_file = preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
return $new_file;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment