Google Analytics PHP Tracking Code

This PHP script creates a 1x1 invisible image __utm.gif for tracking print usage using Google Analytics.

The Google Analytics Profile ID and the Landing Page URL are passed to the script via GET Parameters while the Referrer and User Agent string are determined from the request headers.

/*
* Code modified by @labnol to add print tracking
* version 1.0 date 01/03/2012
* based on PHP Mobile Tracking code by Google.
*/

  define("VERSION", "4.4sh");
  define("COOKIE_NAME", "__utmprint");

  define("COOKIE_PATH", "/");

  // Two years in seconds.
  define("COOKIE_USER_PERSISTENCE", 63072000);

  // 1x1 transparent GIF
  $GIF_DATA = array(
      chr(0x47), chr(0x49), chr(0x46), chr(0x38), chr(0x39), chr(0x61),
      chr(0x01), chr(0x00), chr(0x01), chr(0x00), chr(0x80), chr(0xff),
      chr(0x00), chr(0xff), chr(0xff), chr(0xff), chr(0x00), chr(0x00),
      chr(0x00), chr(0x2c), chr(0x00), chr(0x00), chr(0x00), chr(0x00),
      chr(0x01), chr(0x00), chr(0x01), chr(0x00), chr(0x00), chr(0x02),
      chr(0x02), chr(0x44), chr(0x01), chr(0x00), chr(0x3b)
  );

  // The last octect of the IP address is removed to anonymize the user.
  function getIP($remoteAddress) {
    if (empty($remoteAddress)) {
      return "";
    }

    // Capture the first three octects of the IP address
    // and replace the forth with 0
    $regex = "/^([^.]+\.[^.]+\.[^.]+\.).*/";
    if (preg_match($regex, $remoteAddress, $matches)) {
      return $matches[1] . "0";
    } else {
      return "";
    }
  }

  // Generate a visitor id for this hit.
  // If there is a visitor id in the cookie, use that, otherwise
  // use the guid if we have one, otherwise use a random number.
  function getVisitorId($guid, $account, $userAgent, $cookie) {

    // If there is a value in the cookie, don't change it.
    if (!empty($cookie)) {
      return $cookie;
    }

    $message = "";
    if (!empty($guid)) {
      // Create the visitor id using the guid.
      $message = $guid . $account;
    } else {
      // otherwise this is a new user, create a new random id.
      $message = $userAgent . uniqid(getRandomNumber(), true);
    }

    $md5String = md5($message);

    return "0x" . substr($md5String, 0, 16);
  }

  // Get a random number string.
  function getRandomNumber() {
    return rand(0, 0x7fffffff);
  }

  // Writes the bytes of a 1x1 transparent gif into the response.
  function writeGifData() {
    global $GIF_DATA;
    header("Content-Type: image/gif");
    header("Cache-Control: " .
           "private, no-cache, no-cache=Set-Cookie, proxy-revalidate");
    header("Pragma: no-cache");
    header("Expires: Wed, 17 Sep 1975 21:32:10 GMT");
    echo join($GIF_DATA);
  }

  // Make a tracking request to Google Analytics from this server.
  // Copies the headers from the original request to the new one.
  // If request containg utmdebug parameter, exceptions encountered
  // communicating with Google Analytics are thown.
  function sendRequestToGoogleAnalytics($utmUrl) {
    $options = array(
      "http" => array(
          "method" => "GET",
          "user_agent" => $_SERVER["HTTP_USER_AGENT"],
          "header" => ("Accept-Language: " .
                          $_SERVER["HTTP_ACCEPT_LANGUAGE"]))
    );
    if (!empty($_GET["utmdebug"])) {
      $data = file_get_contents(
          $utmUrl, false, stream_context_create($options));
    } else {
      $data = @file_get_contents(
          $utmUrl, false, stream_context_create($options));
    }
  }

  // Track a page view, updates all the cookies and campaign tracker,
  // makes a server side request to Google Analytics and writes the
  // transparent gif byte data to the response.
  function trackPageView() {
    $timeStamp = time();
    $domainName = $_GET["d"];
    if (empty($domainName)) {
      $domainName = "";
    }

    // Get the referrer from the utmr parameter
    $documentReferer = $_GET["utmr"];
    if (empty($documentReferer) && $documentReferer !== "0") {
      $documentReferer = "-";
    } else {
      $documentReferer = urldecode($documentReferer);
    }

    $documentPath = '/print' . urldecode($_GET["u"]);

    $account = $_GET["id"];
    $userAgent = $_SERVER["HTTP_USER_AGENT"];
    if (empty($userAgent)) {
      $userAgent = "";
    }

    // Try and get visitor cookie from the request.
    $cookie = $_COOKIE[COOKIE_NAME];

    $guidHeader = $_SERVER["HTTP_X_DCMGUID"];
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_UP_SUBNO"];
    }
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_JPHONE_UID"];
    }
    if (empty($guidHeader)) {
      $guidHeader = $_SERVER["HTTP_X_EM_UID"];
    }

    $visitorId = getVisitorId($guidHeader, $account, $userAgent, $cookie);

    // Always try and add the cookie to the response.
    setrawcookie(
        COOKIE_NAME,
        $visitorId,
        $timeStamp + COOKIE_USER_PERSISTENCE,
        COOKIE_PATH);

    $utmGifLocation = "http://www.google-analytics.com/__utm.gif";

    // Construct the gif hit url.
    $utmUrl = $utmGifLocation . "?" .
        "utmwv=" . VERSION .
        "&utmn=" . getRandomNumber() .
        "&utmhn=" . urlencode($domainName) .
        "&utmr=" . urlencode($documentReferer) .
        "&utmp=" . urlencode($documentPath) .
        "&utmac=" . $account .
        "&utmcc=__utma%3D999.999.999.999.999.1%3B" .
        "&utmvid=" . $visitorId .
        "&utmip=" . getIP($_SERVER["REMOTE_ADDR"]);

    sendRequestToGoogleAnalytics($utmUrl);

    writeGifData();
  }
?>
Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

0

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards in 2017.

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

Sign up for our email newsletter to stay up to date.

We will never send any spam emails. Promise.