Skip to content

Instantly share code, notes, and snippets.

@sumonst21
Last active April 3, 2023 00:15
Show Gist options
  • Save sumonst21/696dbbf03eaccf09667f60acb9f539e1 to your computer and use it in GitHub Desktop.
Save sumonst21/696dbbf03eaccf09667f60acb9f539e1 to your computer and use it in GitHub Desktop.
<?php
/**
* function for versioning static assets (images, css, js, etc.) by appending a file's last modified time to the filename (e.g. style.1234567890.css)
* Requires Custom Htaccess rules to be in place (see below)
* Apache .htaccess rules:
* <IfModule mod_rewrite.c>
* RewriteEngine On
* RewriteCond %{REQUEST_FILENAME} !-f
* RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1.$3 [L]
* # to append apply on certain paths only, use the following:
* # RewriteRule ^(/path/to/asset/)(.+)\.(\d+)\.(js|css|png|jpg|gif)$ $1$2.$4 [L]
* </IfModule>
*
* Usage:
* <link rel="stylesheet" href="/css/<?= versioned_asset('style.css', 'css', 'css/') ?>" />
* <script src="/js/<?= versioned_asset('script.js', 'js', 'js/') ?>"></script>
* <img src="/img/<?= versioned_asset('logo.png', 'img', 'img/') ?>" />
*
* @param string $filename The filename of the asset
* @param string $type The type of asset (css, js, img, etc.)
* @param string $path The path to the asset
* @return string The versioned filename
*
* @link https://gist.github.com/sumonst21/696dbbf03eaccf09667f60acb9f539e1
* @copyright Copyright (c) 2022 Sumon Islam (sumonst21)
*/
function versioned_asset($filename, $type, $path = '') {
$file = $path . $filename;
$version = filemtime($file);
$versioned_file = $filename . '.' . $version . '.' . $type;
return $versioned_file;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment