Say you're creating a purely static website on a regular old php-enabled webhost. Let's say you're doing this with iWeb on Dreamhost for some reason. Don't ask.
Now say you want to track the site with Google Analytics. iWeb has no way to insert raw code, and definitely no way to do it across all pages.
Try this...
.htaccess
# Interpret html as php
AddHandler application/x-httpd-php .html
# Required so the xml prolog isn't intepreted as php
php_flag short_open_tag false
# Wrap all requests and add google analytics tracking code
php_value auto_prepend_file '_prepend.php'
php_value auto_append_file '_append.php'
_prepend.php
<?php
ob_start();
?>
_append.php
<?php
$body = ob_get_contents();
ob_end_clean();
# If the page has a </body> tag
if (preg_match('/<\/body>/', $body)) {
# get the GA script tags
ob_start();
include("_google_analytics.txt");
$google_analytics = ob_get_contents();
ob_end_clean();
# Add GA to the document
$body_with_analytics = preg_replace('/<\/body>/', "$google_analytics</body>", $body);
# Write the page with GA
print($body_with_analytics);
# Else just write the page
} else {
print($body);
}
?>
Automatic Analytics Tracking Code Insertion with PHP
Say you're creating a purely static website on a regular old php-enabled webhost. Let's say you're doing this with iWeb on Dreamhost for some reason. Don't ask.
Now say you want to track the site with Google Analytics. iWeb has no way to insert raw code, and definitely no way to do it across all pages.
Try this...
.htaccess_prepend.php_append.php<?php $body = ob_get_contents(); ob_end_clean(); # If the page has a </body> tag if (preg_match('/<\/body>/', $body)) { # get the GA script tags ob_start(); include("_google_analytics.txt"); $google_analytics = ob_get_contents(); ob_end_clean(); # Add GA to the document $body_with_analytics = preg_replace('/<\/body>/', "$google_analytics</body>", $body); # Write the page with GA print($body_with_analytics); # Else just write the page } else { print($body); } ?>_google_analytics.txtHey, it works.