Resurrection Web Design

  • portfolio
  • philosophy
  • services
  • tutorials
  • sign in
Home

Injecting Google Analytics Without Changing Files

tbolton — Tue, 10/26/2010 - 21:33

Have you ever had to take over a website before? Have you ever had to take over a website by someone that didn't follow best practices? It can be a painful thing.

I recently "inherited" a website that had over 1,500 pages to it. Almost every page was done with Microsoft Frontpage, Dreamweaver and believe it or not, Microsoft Word. There was no consistency and nothing was modular about it, which makes site-wide changes rather difficult.

When I had inherited this website, my client asked me to add Google Analytics to it. After looking for a smart way to do this via Google itself and by searching her, I came to the answer that there isn't really a good way to do this, other than modifying a footer page (which we didn't have) or setting up a Server Side Include with a variable placeholder in the text (which would have entailed modifying all 1,500 pages).

So once again, I fell back on the trusty .htaccess file. This file has come in more than handy in my life as a web developer, so I hope you get to know it too.

The .htaccess file lets you run Apache directives without messing with your Apache config file. These directives in .htaccess files will work on the directory level that they're at and all the levels below them, until another .htaccess declares something different.

So what we're going to do today is work with the AddHandler Directive, php_value, auto_prepend_file and auto_append_file.

These four guys are going to make our lives much easier. So let's get started!

.htaccess

Options +Includes
AddHandler server-parsed .html
AddHandler application/x-httpd-php .html
php_value auto_prepend_file /home/userdir/public_html/ga-1.php
php_value auto_append_file /home/userdir/public_html/ga.php

What these five lines do for us are what allow us to insert code without having to edit any of the files. So, as usual, we will go through this line-by-line so we know what we're doing, instead of blindly inserting code.

Options +Includes

This turns on the "INCLUDES" filter in Apache, allowing us to do Server Side Includes.

AddHandler server-parsed .html

Apache gives this for its reference for the AddHandler Directive: Files having the name extension will be served by the specified handler-name.

That's pretty straight forward. So, we're looking for something that is going to handle our HTML files. Notice that this is going to handle every single HTML file that we serve, as long as we don't change the directive. And keep in mind that this is only going to serve HTML files this way. So if we're using a different format (think PHP, ASP, SHTML, etc.), they're not going to get treated the same way. That's obvious, but sometimes people have HTML files as their static pages, and .php files for the shopping cart section of their website.

So, we're using the "server-parsed" handler for the HTML files. This means the server is going to go through each HTML file before it sends it out to the one requesting the page for your site.

AddHandler application/x-httpd-php .html

We are setting up another handler, this time, we're saying that we want to have our HTML files run through the PHP handler. While this may seem strange, it is a crucial step to what we're doing. We are doing this because we are going to be searching and replacing. We aren't doing anything which is complex enough to require RegEx, but don't fret, we'll use them again soon enough.

There is also a performance hit that we're going to notice too. When each page is requested, instead of just going on its normal route to the client, it has to go through the PHP engine first. This takes time for rendering. It isn't particularly noticeable most of the time, but it is something that should be brought up.

php_value auto_prepend_file /home/userdir/public_html/ga-1.php

This can be done when PHP is run as an Apache module. Here's the PHP man page for PHP as an Apache Module. Here is a complete list of all the php.ini directives.

So, what php_value does is set the value for a specific directive. We're working with "auto_prepend_file", which is like PHP's include function, only this puts the file as the very first thing, hence the name "auto_prepend_file". We're telling the server to include or "prepend" our "ga-1.php" file.

php_value auto_append_file /home/userdir/public_html/ga.php

This is just like the previous line, only now we're appending the file, or putting it last.

So that's the tricky part. Now all we have to do is write the scripts!

ga-1.php

<?php

function google_analytics($buffer) {
$ga = <<<END
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js'; type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("GOOGLE_TRACKING_CODE_GOES_HERE");
pageTracker._trackPageview();
} catch(err) {}</script>
END;

return str_ireplace("</body>", "{$ga}</body>", $buffer);

}
ob_start("google_analytics");

?>

This is our precious "ga-1.php" file that we're prepending to everything. This file uses what is called "output buffering". And we're using that to take control of the page as it is processed, store it in a buffer, perform a case insensitive search for "", and insert the Google Analytics code before it when we find it.

The ob_start function uses what is called a "callback function". Callback functions are nice because you can define what you want to happen, while incorporating it with a pre-written PHP function. Life is good. Our particular callback function just returns the replaced text, which happens to contain our GA code.

ga.php

<?php

ob_end_flush();

?>

This is appended to the script. It is simply the ob_end_flush function, and all it does is tell PHP to stop the buffer and send it to the client. We know the page has finished loading and we've got the entire HTML file, because we have this appended (or added to the end) of the HTML file itself. Pretty clever, huh? Well, I'm sure there are others out there doing the same thing. But this trick saved me hours of work, much of my sanity, and decreased my likelihood on an early onset of CTS.

  • Login to post comments

Contact Us

Phone: 224-678-1213 sales@resurrectionwebdesign.com

Resurrection Web Design
Elgin,  IL 60123-2669
United States of America
Telephone: 224-678-1213
sales@resurrectionwebdesign.com

  • Custom CMS
  • Drupal
  • Magento
  • Miva Merchant
  • Pure HTML / CSS
  • WordPress

  • Custom Modules
  • Development
  • Redesign
  • SEM
  • SEO
  • Text Messaging
  • VoIP
  • portfolio
  • philosophy
  • services
  • tutorials
  • sign in