Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active October 30, 2016 17:32
Show Gist options
  • Save surferxo3/25ecb190046589b38e457f653a2153c3 to your computer and use it in GitHub Desktop.
Save surferxo3/25ecb190046589b38e457f653a2153c3 to your computer and use it in GitHub Desktop.
A class to track campaign and visitors source via session.
<?php
/*
* Developer: Mohammad Sharaf Ali
* Version: 1.0
* Description: Demo Page displaying actual MTracker class usage
* Dated: 03-02-2016
*/
/*
** Use the code on the actual registration or whatever page you want to track than get the details using STEP5 and save it to db / file as per your requirements.
** Things to remember:
- STEP 4 will start the session once and save all the relevant info in session. Calling it on every page will not affect the data saved on the
first instance.
- STEP 5 will return the saved data in the session. The "true" parameter plays an important role in a sense, if suppose on page 1 you passed in it as "true" it
will save the url in the session as "page1.php" and on the page 2 again you passed in it as "true" so it will override and save in the session as "page 2". Leaving
it blank or passing in as "false" will pertain "page1.php".
- The flow of the script is simple:
- First it will look for UTM parameters in the url. If found okay else
- It will look HTTP_REFERER in the http headers. If found okay else
- It will set the default values as set in MTracker.php class
** With this script you can track more of the things you want with a little customization and build beautiful dashboards to analyze your data.
*/
#STEP 0: Ensure you are using UTM url's as that is the way the script will track your campaign and visitors source
#STEP1: include the lib
require_once 'MTracker.php';
#STEP2: create namespace alias to access the class
use MSharaf\MTracker as MTracker;
#STEP3: create singleton class object
$coolTracker = MTracker::getInstance();
#STEP4: start the tracker
# session name (optional) {The session name can't consist of digits only, at least one letter must be present.}
$coolTracker->startTracker('any2016');
#STEP5: get the tracker tracked data
# track page url (optional) {true, false}
print_r($coolTracker->getTracker(true));
<?php
/*
* Developer: Mohammad Sharaf Ali
* Version: 1.0
* Description: Class to track visitor registration source
* Dated: 23-04-2016
*/
namespace MSharaf;
class MTracker
{
private static $instance;
private static $defaultSource = 'Any';
private static $defaultMedium = 'Direct Link';
private function __construct()
{
}
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new MTracker();
}
return self::$instance;
}
private function initSession($name = '')
{
$phpVersion = phpversion();
if ($phpVersion < '5.4.0') {
if (session_id() == '') {
if (!empty($name)) {
session_name($name);
}
session_start();
}
} else if ($phpVersion >= '5.4.0') {
if (session_status() == PHP_SESSION_NONE) {
if (!empty($name)) {
session_name($name);
}
session_start();
}
}
}
private function unsetSessionVars($vars)
{
foreach ($vars as $var) {
unset($_SESSION["{$var}"]);
}
}
private function destroySession()
{
session_unset();
session_destroy();
}
private function getName($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return explode('.', $regs['domain'])[0];
}
return false;
}
public function getSiteUrl($customUri = '')
{
$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https://' : 'http://';
if (empty($customUri)) {
return ($scheme . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
} else {
return ($scheme . $_SERVER['HTTP_HOST'] . $customUri);
}
}
private function getHostAndKeyword($url = '')
{
$output = array(self::$defaultSource, self::$defaultMedium);
$matches = array();
$referrer = (!empty($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : '';
$referrer = (!empty($url)) ? $url : $referrer;
if (empty($referrer)) {
return $output;
}
$parsedUrl = parse_url($referrer);
if (empty($parsedUrl['host'])) {
return $output;
}
$host = $parsedUrl['host'];
$queryStr = (!empty($parsedUrl['query'])) ? $parsedUrl['query'] : '';
$queryStr = (empty($queryStr) && !empty($queryStr['fragment'])) ? $queryStr['fragment'] : $queryStr;
if (empty($queryStr)) {
$output = array(
$this->getName($referrer) !== false ? $this->getName($referrer) : self::$defaultSource, '');
return $output;
}
parse_str($queryStr, $query);
$searchEngines = array(
'q' => 'alltheweb|aol|ask|lycos|hotbot|infospace|looksmart|dogpile|gigablast|webcrawler|contenko|alhea|zapmeta|teoma|duckduckgo|bestsearch|entireweb|msn|bing|google',
'p' => 'yahoo',
'wd' => 'baidu',
'text' => 'yandex',
'qs' => 'virgilio',
'searchfor' => 'mywebsearch',
'qkw' => 'info',
'query' => 'carrot2|yippy|iseek|startpage'
);
foreach ($searchEngines as $queryVar => $se) {
$se = trim($se);
preg_match('/(' . $se . ')\./', $host, $matches);
if (!empty($matches[1]) && !empty($query[$queryVar])) {
$output = array(
$this->getName($referrer) !== false ? $this->getName($referrer) : self::$defaultSource,
$query[$queryVar]);
return $output;
}
}
if (empty($matches)) {
$output = array(
$this->getName($referrer) !== false ? $this->getName($referrer) : self::$defaultSource, '');
return $output;
}
}
private function setTracker()
{
$parsedUrl = parse_url($this->getSiteUrl());
if (isset($parsedUrl['query'])) {
parse_str($parsedUrl['query'], $parsedQueryStrArr);
}
if (isset($parsedQueryStrArr) && !empty($parsedQueryStrArr) &&
isset($parsedQueryStrArr['utm_source']) && !empty($parsedQueryStrArr['utm_source']) &&
isset($parsedQueryStrArr['utm_medium']) && !empty($parsedQueryStrArr['utm_medium'])) {
$_SESSION['SessData']['Tracker'] = array(
'Source' => isset($parsedQueryStrArr['utm_source']) ? urldecode($parsedQueryStrArr['utm_source']) : self::$defaultSource,
'Medium' => isset($parsedQueryStrArr['utm_medium']) ? urldecode($parsedQueryStrArr['utm_medium']) : self::$defaultMedium,
'QueryString' => isset($parsedQueryStrArr['utm_source']) ? '?'. $parsedUrl['query'] : '?v='. self::$defaultSource);
} else if(isset($_SERVER['HTTP_REFERER']) && $this->getName($_SERVER['HTTP_REFERER']) != $this->getName($this->getSiteUrl())) {
list($host, $keyword) = $this->getHostAndKeyword();
$_SESSION['SessData']['Tracker'] = array(
'Source' => isset($host) && !empty($host) ? $host : self::$defaultSource,
'Medium' => isset($keyword) && !empty($keyword) ? urldecode($keyword) : '',
'QueryString' => '?v='. self::$defaultSource);
} else {
$_SESSION['SessData']['Tracker'] = array(
'Source' => self::$defaultSource,
'Medium' => self::$defaultMedium,
'QueryString' => '?v='. self::$defaultSource);
}
}
public function startTracker($sessName = '')
{
$this->initSession($sessName);
if (!isset($_SESSION['SessData'])) {
$this->setTracker();
} else if(isset($_SESSION['SessData']) && empty($_SESSION['SessData']['Tracker']['Source'])) { // could also check for other parameters
$this->destroySession();
$this->initSession($sessName);
$this->setTracker();
}
}
public function getTracker($withTrackUrl = false)
{
if ($withTrackUrl === true) {
$finalUrl = $this->getSiteUrl();
$urlWithoutUri = strtok($finalUrl, '?');
if ($urlWithoutUri !== false) {
$finalUrl = $urlWithoutUri. $_SESSION['SessData']['Tracker']['QueryString'];
}
$_SESSION['SessData']['Tracker']['Url'] = $finalUrl;
}
return $_SESSION['SessData']['Tracker'];
}
}
@surferxo3
Copy link
Author

With a little customization from your end you can use easily convert the session based logic to cookie based logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment