Ajaxorized

Include Google Analytics in your static HTML website

July 10, 2007

A few months ago I was assigned to a project where a company, while their new site was being developed, wanted to track the visitors on their website for marketing purposes. The only problem was that their current website was constructed with Frontpage a few years ago and consisted of hundreds of static HTML pages. Since I'm (very) lazy I was not planning to copy paste the whole thing, I figured out a way to include the GA code in every static html page.

First, I wrote a .htaccess file which rewrites all (including files in subdirs) .html and .htm pages to addgoogleanalytics.php:

RewriteEngine on
RewriteRule ^(.*).html?$ addgoogleanalytics.php?file=$0

Wow, it that all? Yes it is. So helloworld.html will be rewrited to addgoogleanalytics.php?file=helloworld.html, and the user won't even notice. Now, take a look at addgoogleanalytics.php:

<?php
/* Open the given file and add the google analytics code */
$sData = file_get_contents($_GET['file']);
$sData = str_replace("</body>", "
<script src=\"http://www.google-analytics.com/urchin.js\" type=\"text/javascript\">
</script>
<script type=\"text/javascript\">
_uacct = \"UA-1808705-3\";
urchinTracker();
</script>
 
</body>", $sData);
echo $sData;
?>

Enjoy.

Add to: del.icio.us Reddit Slashdot Digg Facebook Technorati Google StumbleUpon Windows Live Yahoo
topFiled under: Uncategorized, PHP, Apache, Code | Willem @ 12:10 pm | Comments (1)