2

I'm using a PHP script along with some .htaccess rules for cache busting for automatically versioning files on a static website.

The source of the script is here: http://www.particletree.com/notebook/automatically-version-your-css-and-javascript-files/

I changed the names of variables and functions, but I don't think that's the problem.

Script in header.php:

<?php
function VERSIONING($url){
$path = pathinfo($url);
$ver = '.'.filemtime($_SERVER['DOCUMENT_ROOT'].$url).'.';
echo $path['dirname'].'/'.str_replace('.', $ver, $path['basename']);
}
?>

using the function on script, css, etc. in header.php:

<?php VERSIONING('/resources/css/stylesheet.css'); ?>
<?php VERSIONING('/resources/js/script.js'); ?>
<?php VERSIONING('/resources/img/logo.png'); ?>

.htaccess rules for cache busting:

<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)\.(\d+)\.(js|css|jpe?g|png|gif|ico)$ $1.$3 [L]
</IfModule>

Now here's the problem. It works just fine, but every 10-24 or so hours, I receive errors in my error_log file for each file I'm using VERSIONING on.

Each error looks like this:

[16-Mar-2013 09:06:24] PHP Warning:  filemtime(): stat failed for /usr/local/apache/htdocs/resources/js/script.js in /home5/username/public_html/resources/header.php on line 42

And line 42 contains the following:

$ver = '.'.filemtime($_SERVER['DOCUMENT_ROOT'].$url).'.';

I have no idea what the problem could be. My only guess is that the DOCUMENT_ROOT is being interpreted differently sometimes, and failing to properly locate the files during versioning.

Any ideas?

questy
  • 517
  • 2
  • 4
  • 14
  • The file doesn't exist. No status (stat) can be read from a file that does not exist. – Bart Mar 18 '13 at 20:50
  • Oh, I see. What would the proper syntax be for manually defining the root of the website, or file path? – questy Mar 18 '13 at 20:52
  • Something like: `$ver = file_exists($versionedFile) ? 1 : readVersion();` http://php.net/manual/en/function.file-exists.php – Bart Mar 18 '13 at 20:59

1 Answers1

1

It looks like your problem is that you are passing a relative URL to your versioning function, that requires a file path on the disc, and/or you are on a shared platform and $_SERVER['DOCUMENT_ROOT'] is for the root of the server rather than your site

as a quickish fix I would define a constant, for your root, looks like it might be this

define('SITE_ROOT', '/home5/username/public_html');

then try

function VERSIONING($url){
  $path = SITE_ROOT.$url;
  $ver = '.'.filemtime($path).'.';
  echo str_replace('.', $ver, $url);
}
CodeMonkey
  • 3,271
  • 25
  • 50