Skip to content

Instantly share code, notes, and snippets.

@openprojdev
Created July 29, 2013 15:43
Show Gist options
  • Save openprojdev/6105277 to your computer and use it in GitHub Desktop.
Save openprojdev/6105277 to your computer and use it in GitHub Desktop.

Revisions

  1. openprojdev created this gist Jul 29, 2013.
    50 changes: 50 additions & 0 deletions gistfile1.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    <?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');

    ?>