PHP: Add Google Analytics to an entire static HTML website with PHP

June 14, 2010

I am in a situation where I need analytics data and none is provided. The entire 35k+ file website is all static HTML running on a Windows IIS server. I am not familiar enough with Windows Server to know what sort of scripting capabilities there are, but I do have PHP available. I wrote a simple script that uses the PHP 5 RecursiveDirectorIterator to look through the entire site and append the Google Analytics code to the closing body tag. It then rewrites the file it is looking at.

If you are stuck in a similar situation where you do not have scripting abilities you may want to consider giving this script a go, or altering it to fit whatever language you are using. Works like a charm.

$directory = 'where your files are';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

while($it->valid()) {

    if (!$it->isDot()) {
        $c = file_get_contents($it->key());
        $c = str_replace('', YOUR ANALYTICS CODE HERE . '', $c);
        $fh = fopen($it->key(), 'w');
        fwrite($fh, $c);
        fclose($fh);
        echo "Replaced body in: " . $it->key();
    }

    $it->next();
}

Might be worth it to ensure you are looking only at .html and .htm files if you have a complex set. Additionally, if you have a very large set of files you may need to look at timeout issues.