Skip to content

Instantly share code, notes, and snippets.

@Darep
Last active April 23, 2024 07:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Darep/4627661 to your computer and use it in GitHub Desktop.
Save Darep/4627661 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;
}
@Darep
Copy link
Author

Darep commented Jan 24, 2013

Usage e.g. <link rel="stylesheet" href="<?php echo auto_version('/css/main.css'); ?>" type="text/css" />

@teknosains
Copy link

Where is the Server config? Apache or nginx?

@Darep
Copy link
Author

Darep commented Jul 24, 2017

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]

@lanangbtw
Copy link

what if base_url with port number? like
http://localhost:8080/
? i have been try and it is failed
thank you very much

@Lovor01
Copy link

Lovor01 commented Apr 8, 2020

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