Last active
April 23, 2024 07:16
-
-
Save Darep/4627661 to your computer and use it in GitHub Desktop.
PHP CSS&JS auto-versioning function.
This file contains hidden or 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
# CSS/JS auto-versioning | |
RewriteEngine On | |
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L] |
This file contains hidden or 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 | |
/** | |
* 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; | |
} |
Where is the Server config? Apache or nginx?
Server config for Apache below, place into .htaccess
, site config or any Apache config that works for you :)
# CSS/JS auto-versioning
RewriteEngine On
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]
what if base_url with port number? like
http://localhost:8080/
? i have been try and it is failed
thank you very much
I found it not to work with relative paths and on my system (Windows 10, Apache), but I would say it will not work on linux server neither with relative paths. I fixed the code, see my fork, I suggest you merge it to your code.
Cheers
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage e.g.
<link rel="stylesheet" href="<?php echo auto_version('/css/main.css'); ?>" type="text/css" />