Track and log your website's traffic with the TrafficTracker PHP class and Google Analytics

TrafficTracker is a simple PHP class to track a website's traffic and then log to a database by parsing cookies and custom URL parameters. The class utilizes cookies set by the typical Google Analytics tracking code initialization. In addition, if you deploy Google AdWords

PPCPay-Per-Click
campaigns to drive traffic to your website, the class will (along with custom URL parameters added to your destination URLs) track the hits from your AdWords campaigns.

Requirements

  • Web Server / Hosting account running PHP 5+
  • Website pages capable of running PHP server-side code (usually ending in .php) and JavaScript
  • Google Analytics tracking code initialized on all website pages
  • If using Google AdWords, you must append each keyword's destination URL with the custom URL parameters outlined below

How It Works

The class writes to a MySQL database table, saving values for every page visit for the following attributes.

KeyDescriptionValue
idAuto-increment idExample: 987654
identifyUserUnique ID for each visitor, generated by Google Analytics.Example: 1234567890
mediumEvery referral to a website has a medium of arrivalorganic - Unpaid search.
cpc - Cost per click, i.e. paid search.
referral - Referral.
email - Name of a custom medium you created.
none - Direct visits.
sourceThe origin (or source) of the referraldirect - Visits from people who typed your URL directly into their browser, or who had bookmarked your site.
google - The name of a referring search engine.
example.com - The name of a referring site.
contentIdentifies a specific link or content item, such as a specific page on a referring site or link in a custom campaign.Example: /page-with-link-to-you.html
campaignThe name of the referring AdWords campaign or a custom campaign that you have created.Example: July Banner Ad
keywordThe actual exact search term(s) the user entered into a search engine to eventually reach your website (excluding Google AdWords keywords)Example: bike storage hanger for wall
pageViewedThe page on your website viewed for the recorded visit.Example: http://www.example.com/page-one.php
adwordsKeywordThe keyword or keyword phrase in your Google AdWords campaign that was triggered by the visitors actual search term(s) (see keyword).Example: bike storage hanger
adwordsMatchTypeThe type of match that triggered your AdWords keyword.e - exact
p- phrase
b - broad
adwordsPositionThe position on the page that your ad appeared in, with a value such as 1t2, which is equivalent to page 1, top, pos 2.Example: 1t2
firstVisitThe timestamp indicating the visitor's first visit to your website when their cookies were created for your website.date with format: 0000-00-00 00:00:00
previousVisitThe timestamp for the visitor's last visit to your website, besides the current one.date with format: 0000-00-00 00:00:00
currentVisitThe timestamp of the visitor's current visit to your website which is being logged.date with format: 0000-00-00 00:00:00
timesVisitedThe number of times the visitor viewed a specific page on your site.Example: 3
pagesViewedThe total number of pages visited.Example: 12
userIpThe IP address of the visitorExample: 10.0.0.1
timestampThe timestamp of the logged visit.date with format: 0000-00-00 00:00:00

Setup

Download the source code, then create a new table on your database called trafficTracker using the SQL statement below

CREATE TABLE IF NOT EXISTS `trafficTracker` (
  `id` int(10) NOT NULL auto_increment,
  `identifyUser` varchar(65) character set utf8 collate utf8_unicode_ci NOT NULL,
  `medium` varchar(50) character set utf8 collate utf8_unicode_ci NOT NULL,
  `source` varchar(60) character set utf8 collate utf8_unicode_ci NOT NULL,
  `content` varchar(150) character set utf8 collate utf8_unicode_ci NOT NULL,
  `campaign` varchar(50) character set utf8 collate utf8_unicode_ci NOT NULL,
  `keyword` varchar(100) character set utf8 collate utf8_unicode_ci NOT NULL,
  `pageViewed` varchar(350) character set utf8 collate utf8_unicode_ci NOT NULL,
  `adwordsKeyword` varchar(75) character set utf8 collate utf8_unicode_ci NOT NULL,
  `adwordsMatchType` varchar(10) character set utf8 collate utf8_unicode_ci NOT NULL,
  `adwordsPosition` varchar(5) NOT NULL,
  `firstVisit` timestamp NOT NULL default '0000-00-00 00:00:00',
  `previousVisit` timestamp NOT NULL default '0000-00-00 00:00:00',
  `currentVisit` timestamp NOT NULL default '0000-00-00 00:00:00',
  `timesVisited` int(4) NOT NULL,
  `pagesViewed` int(6) NOT NULL,
  `userIp` varchar(40) character set utf8 collate utf8_unicode_ci NOT NULL,
  `timestamp` timestamp NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

Open the class.TrafficTracker.php file and edit the top section variables shown here

/* -------------------------------------------------------------------------
------------------------------- SET DEFAULTS -------------------------------
--------------------------------------------------------------------------*/
private $urlPrefix          = 'http'; // Set URL prefix for your website.
private $replaceInUrl       = array('?customer=new','?version=mobile'); // strip out any custom strings from URL.
private $myIp               = array('10.0.0.1'); // Put IP addresses you would like to filter out (not track) in array.
private $reportingTimezone  = 'America/Kentucky/Louisville'; // http://www.php.net/manual/en/timezones.america.php
private $dateFormat         = 'Y-m-d H:i:s'; // Preferred date format - http://php.net/manual/en/function.date.php
private $cookieExpire       = 30; // Set number of days for AdWords tracking cookies to be valid.

Simply include the class above the head of your PHP page with the following snippet

include_once('../path/to/class.TrafficTracker.php');

Next, initialize the class with arguments

$trafficTracker = new TrafficTracker(
    $dbHost, // Your Database Host
    $dbUsername, // Your Database Username
    $dbPassword, // Your Database Password
    $dbDatabase, // Your Database Name
    $trackPrefix, // Preferred prefix for URL parameters and browser cookies
    $deleteRollingDays // Delete database records older than {$deleteRollingDays} days
);

The first 4 arguments define the connection to your database. The 4th argument $trackPrefix will be used as the prefix for your Google AdWords destination URL custom parameters, as well as for the cookies set in the visitor's browser. The default value (if unset) is ttcpc. The 5th argument, $deleteRollingDays, is an integer value that designates the number of rolling days to go back before deleting logged visits. The default value for this argument is 30, meaning that any record created greater than 30 days ago from now will be deleted.

Set up Google AdWords Destination URLs

If using Google AdWords campaigns to drive traffic to your website, add the following parameters to the end of each destination URL, changing ttcpc in the code below to the value of $trackPrefix if you defined a different string.

?ttcpc=true&ttcpc_kw={keyword}&ttcpc_pos={adposition}&ttcpc_mt={matchtype}

The above URL parameters will cause AdWords to dynamically insert the keyword, ad position, and match type into your URL as values for their allocated parameter.

  • {keyword} - For the search sites, the specific keyword that triggered your ad; for content sites, the best-matching keyword.
  • {adposition} - The position on the page that your ad appeared in, with a value such as 1t2, which is equivalent to page 1, top, pos 2.
  • {matchtype} - The matching option of the keyword that triggered your ad: exact, phrase, or broad.

NOTE

If your AdWords destination URLs already have parameters (i.e.http://www.example.com/index.php?view=3) then just add the TrafficTracker parameters to the end, like shown below.

http://www.example.com/index.php?view=3&ttcpc=true&ttcpc_kw={keyword}&ttcpc_pos={adposition}&ttcpc_mt={matchtype}

Example

  1. Include the class
  2. Initialize the class with your database connection details; optionally changing ttcpc to your desired prefix, and changing the default rolling 30 days delete to 60 days instead.

The top of each page on your site will look similar what is shown below.

// 1. Include class
include_once('../path/to/class.TrafficTracker.php');

// 2. Initialize class with your configuration
$trafficTracker = new TrafficTracker(
    'your_host',
    'your_db_username',
    'your_db_password',
    'your_database',
    'ttcpc',
    60
);

Additional Information

The unique identifier set for each user by Google Analytics $identifyUser is automatically stored in a browser cookie for each visitor which is accessible in PHP or JavaScript.

For example, to access the cookie in PHP, you would use this format:$_COOKIE['ttcpc_id']. Replace ttcpc (default) with the value you set for $trackPrefix.