How I display the Last 10 Referrers list

A few folks have asked how I did the last 10 referrers list that appear over on the right-hand side of all the pages on my site. Well, here it is.

The first thing you need to know is that every page on Dave's Picks goes through a PHP script to render the page. There's more about that in About Dave's Picks. That script includes the following code near the beginning, which saves off every referrer to a minimally formatted HTML file (which is defined right near the top).

$REFFILENAME = "/usr/webstuff/davespicks_reffile.html";

if (isset($HTTP_REFERER) &&
    ($HTTP_REFERER != "") &&
    ($HTTP_REFERER != "bookmarks") &&
    ($content != "addpick.php"))
{
    // I have a referrer I want to save -- save it to the file
    $shortref = preg_replace("/http:\/\//","", $HTTP_REFERER);
    $shortref = preg_replace("/\/.*/", "", $shortref);
    if (($shortref != "davespicks.com") &&
        ($shortref != "www.davespicks.com") &&
        ($shortref != "bookmarks"))
    {
            // quote the &s in URLs to make legal HTML
        $longref = preg_replace("/&/", "&", $HTTP_REFERER);
        $reffile = fopen($REFFILENAME,'a');
        fwrite($reffile, "<a href=\"$longref\">$shortref</a><br>\n");
        fclose($reffile);
    }
}

Since I'm using the template class from PHPLib to do text-substitutions into a standard template, I just have an entry in the template where I plug in the referrers. I'm not going to try and describe how PHPLib templates work, but the following code gets the list that I plug in. I do this just before I emit the page.

    // set up the last 10 referrers list
    $refarray = array();
    exec("/usr/bin/tail $REFFILENAME", $refarray);
    $reflist = implode("\n", $refarray);

That's about it. It's made easier by the fact that I don't need a complete HTML file (even though I call it davespicks_reffile.html) to store the referrer information. There's probably a more efficient way I could be doing it than using tail over and over, but the server logs don't show that heavy of a load from this part of the script, so I'm not worrying about it yet. Avoid Premature Optimizations. The only other thing is that the refs file is never cleared out by this script. I've got some perl scripts that run daily and clean things up for me, but that's another article.

Copyright 2009, Dave Polaschek. Last updated on Mon, 15 Feb 2010 14:09:28.