getButterfly Logo getButterfly

This is a basic affiliate system and it works by setting up a cookie and a database entry, and updating the record if a successful payment has gone through.

First of all, we need to detect if a link with an affiliate parameter has been clicked. So, we place the following code in the header of our template:

<?php
/**
* Custom affiliate conversion tracking code
*/
include WEBSITE_PATH . '/Affiliate.php';

if(isset($_GET['affid'])) {
    // Get affiliate ID
    $affid = filter_var(trim($_GET['affid']), FILTER_SANITIZE_NUMBER_INT);

    affiliateGetVisit($affid);
}

if($url === '/payment-page') {
    if(isset($_COOKIE['AffiliateURL'])) {
        affiliateConvertVisit($_COOKIE['AffiliateID'], $_COOKIE['AffiliateURL'], $conversionValue, $transactionId, $transactionNumber);
    }
}

Note that you will need to make some changes in order to accommodate the code above, namely the $url variable, which holds the current page URL and the $conversionValue, $transactionId and $transactionNumber variables, which hold details related to your own funnel system.

Next, we set up our Affiliate.php file. This file holds lots of helper functions (device detection and database connection) and our main database insert and update routines.

<?php
/**
* Library for affiliate processing
*
* @copyright getButterfly.com 2016
*
*
* Add a parameter to any URL to test custom affiliate tracking
* $url .= (parse_url($url, PHP_URL_QUERY) ? '&' : '?') . 'affid=1';
*
*/

/**
* Get affiliate device (basic).
*
* @return string
*/
function clickIsMobile() {
    return preg_match("/(android|webos|avantgo|iphone|ipad|ipod|blackberry|iemobile|bolt|bost|cricket|docomo|fone|hiptop|mini|opera mini|kitkat|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

/**
* Get affiliate device (extended).
*
* @return string
*/
function clickGetDevice() {
    $userAgent = $_SERVER["HTTP_USER_AGENT"];
    $devicesTypes = array(
        "computer" => array("edge", "msie 11", "msie 10", "msie 9", "msie 8", "windows.*firefox", "windows.*chrome", "x11.*chrome", "x11.*firefox", "macintosh.*chrome", "macintosh.*firefox", "opera"),
        "tablet" => array("tablet", "android", "ipad", "tablet.*firefox"),
        "mobile" => array("mobile ", "android.*mobile", "iphone", "ipod", "opera mobi", "opera mini"),
        "bot" => array("googlebot", "mediapartners-google", "adsbot-google", "duckduckbot", "msnbot", "bingbot", "ask", "facebook", "yahoo", "addthis")
    );
    foreach($devicesTypes as $deviceType => $devices) {
        foreach($devices as $device) {
            if(preg_match("/" . $device . "/i", $userAgent)) {
                $deviceName = $deviceType;
            }
        }
    }

    return ucfirst($deviceName);
}

/**
* Get database connection.
*
* @return object
*/
function clickPdo() {
    $db = new PDO('mysql:host=localhost;dbname=database;charset=utf8', 'user', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    return $db;
}

/**
* Store affiliate visit details in log table.
*
* @param int $affiliateId
* @param string $target
* @return bool
*/
function affiliateGetVisit($affiliateId) {
    $clickUrl = strtok("https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", '?');
    $affiliateClickUrl = $affiliateClickUrl . '?affid=' . $affiliateId;

    setcookie("AffiliateID", $affiliateId, strtotime('+30 days')); // 30 days
    setcookie("AffiliateURL", $clickUrl, strtotime('+30 days')); // 30 days

    $clickIp = $_SERVER['REMOTE_ADDR'];
    $clickReferrer = $_SERVER['HTTP_REFERER'];
    $clickTimestamp = date('Y-m-d H:i:s');

    if(clickIsMobile()) {
        $clickDevice = 'mobile';
    } else {
        $clickDevice = 'desktop';
    }

    $clickGetDevice = clickGetDevice();

    $clickConversion = 0;
    $clickTransactionId = 0;

    $stmt = clickPdo()->prepare("INSERT INTO affiliate_log (
        affiliateId,
        clickReferrer,
        clickTimestamp,
        clickIp,
        clickDevice,
        clickUrl,
        clickConversion,
        clickTransactionId
    ) VALUES (
        '$affiliateId',
        '$clickReferrer',
        '$clickTimestamp',
        '$clickIp',
        '$clickDevice ($clickGetDevice)',
        '$clickUrl',
        '$clickConversion',
        '$clickTransactionId'
    )");
    $stmt->execute();
}

/**
* Update affiliate visit details in log table and remove all cookies. Sugar is bad.
*
* @param int $affiliateId
* @param string $affiliateUrl
* @param int $conversionValue
* @param int $transactionId
* @param string $transactionNumber
* @return bool
*/
function affiliateConvertVisit($affiliateId, $affiliateUrl, $conversionValue, $transactionId, $transactionNumber) {
    $holidayUrl = strtok(urldecode($affiliateUrl), '?');
    $clickIp = $_SERVER['REMOTE_ADDR'];

    $stmt = clickPdo()->prepare("UPDATE affiliate_log SET
        clickConversion = 1,
        clickTransactionId = '$transactionId',
        clickTransactionNo = '$transactionNumber',
        clickTransactionValue = '$conversionValue'
    WHERE
        clickUrl = '$holidayUrl'
        AND affiliateId = $affiliateId
        AND clickIp = '$clickIp'
    LIMIT 1");
    $stmt->execute();

    // Cookie has done its job, remove it
    setcookie('AffiliateID', '', time() - 3600, '/');
    unset($_COOKIE['AffiliateID']);

    setcookie('AffiliateURL', '', time() - 3600, '/');
    unset($_COOKIE['AffiliateURL']);
}
?>

This is my own approach and implementation. It’s basic and it needs more work, but it’s the first step if you want to code your own affiliate tracking system.


Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.



If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply