How to include google analytics code the right way?

It sounds like you are wondering if you can put a php include() into a .html file? If so, the answer is no, you have to rename your index file from index.html to index.php. In fact, any page that you need to include your include() google analytics code needs to have a .php extension.

so:

index.php

<html>
<head>
</head>

<body>
** CONTENT **

<?php include('google.html'); ?>
</body>
</html>

google.html

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "...";
urchinTracker();
</script>

hope that helps… try renaming one of your server files to .php and see if it works (ie: contact.html to contact.php). If so, just rename all your extensions to .php and do a mass find and replace on your website for .html and replace it with .php. Be sure to copy all your files and try to do a replace on a copy of the website.

The calling page (index) needs to be parsed by PHP in order for the include to work.
HTML has no ability to access files on the server like that.

Presumably your site is more than one page, so you’ll need to change everything to PHP in order to be able to reference a single instance of your analytics code.

That creates another problem, which is that if all your .html files become .php you could break a lot of links and loose a lot of search engine position.
You’ll either need to contact your host and ask if they can configure PHP to process html pages (this is possible), which will negate the need to change a lot of extensions, or
you’ll need to use an Apache Mod Rewrite rule so that requests for .html docs are actually processed by the equivalent .php page.
Complex eh?


# example .htaccess file (Apache configuration)
RewriteEngine On
RewriteRule (.+)\\.html$ $1.php

With this .htaccess file you still rename all .html files to .php (no links break).
When I request example.html the page will still load (hooray) even though example.html is now actually example.php
PHP will process the page and your GA include will work.

Thanks! can’t name page to .php as there are many incoming links.

Hi Santhi,

         Once got the Google analysis code, you can put the code before closing [&lt;/body&gt;] body tag. like past the code like:

<script src=“#” type=“text/javascript”>
</script>
<script type=“text/javascript”>
_uacct = “…”;
urchinTracker();
</script>

yes u can rename them, use mod rewrite to redirect those incoming links to a php extension instead! do it! :wink: