Build Your Own PHP Affiliate Tracker – The Redirect Link

I’m going to continue down the road of sharing some of the coding knowledge I’ve been slowly picking up with my next Affiliate Hack – setting up your first tracking link.

The tracking link is perhaps the most fundamental piece of building your own tracker, as it’s the first tangible piece of your campaign as well as the last (you send a user to your page using a tracking link and then send them off to the offer via your tracking link). Rather than start from the beginning and write out a sequential guide to building a tracker, I’m just going to share what a basic tracking link looks like and how you can use it in your affiliate campaigns. Like I said the essence of all PHP trackers are built on this so it’s good knowledge to start with.

There are free trackers out there like Prosper202, but using your own tracking is challenging, rewarding, and can offer a more robust and customized product for yourself.

Split Testing Headlines with a Tracking Link

For this example I’m going to show you how you can test multiple headlines on your landing page and track which one leads to more sales. Say we have a page selling Printer Ink (hey that was big online in like 2006 remember?), and we want to test a few headlines at the top of our page and see how they perform. We want to test these 3 headlines:

  • $49 Printer Ink Blowout!
  • Cheap Brand Name Ink
  • Clearance Sale on Ink (50% Off)

The first question is: How do we rotate these 3 headlines on our page? Which then follows up with the question Once they’re rotating, how do I actually track performance? Let’s break down each question:

How do we rotate these 3 headlines on our page?

This problem has a pretty easy solution with PHP using PHP arrays and a couple nifty functions. Here’s the code you’ll place at the very top of your landing page:

$h1 = "$49 Printer Ink Blowout!";
$h2 = "Cheap Brand Name Ink";
$h3 = "Clearance Sale on Ink (50% Off)";

$headlines = array(
array('h1', $h1),
array('h2', $h2),
array('h3', $h3)

$c = count($headlines)-1;
$headline = $headlines[rand(0,$c)];

Let’s break down what we’re doing line by line:

The $h1-$h3 lines : These lines simply define the headlines we’re split testing. The first headline would be called with $h1 so that if you ran the code ‘echo $h1′, the screen would display “$49 Printer Ink Blowout!”.

The $headlines array : this is where we create the array (kind of like a container or bucket) to store our headlines. This is a multidimensional array (a bucket with a bucket inside of it) that initially complicates things a bit more but will save us time in the end. Our $headlines array contains 3 arrays within it, 1 for each headline. The individual arrays store two things, first ‘h1′, which is just the name we’re going to use to track the headline (you can make this whatever you want). That way when we run a report in our affiliate network, the subid will show up as “h1″ so that you know the sale came from that headline. The second part of the array stores the headline itself, which are the variables we defined at the top.

Setting the count ($c) : The next thing we’ll do to simplify our code is take a basic count of all of our headlines so that we can pick one randomly. The count($headlines) function will tell us that there are 3 headlines to pick from, we then add -1 at the end because arrays start with 0, meaning our headlines are actually 0,1,2 and not 1,2,3. The -1 tells $c that the count ends at 2 instead of 3 so that we don’t echo out a headline that doesn’t exist (blank).

Setting the $headline : Now we get to randomly select our headline. $headlines[rand(0,$c)]; tells us to first look at our $headlines array (which contains the split tests) and then select randomly between 0 and 2 (remember our headlines are 0,1,2 so we’re getting all 3 here).

Now we’ve randomly selected our headline! It’s time to use it. From the code above we’ve produced two tangible variables:


When you want to use the actual headline in your page and display it, simply paste this:

<? echo $headline[1]; ?>

That’s going to pull our randomly selected headline array and echo the SECOND value, which is the headline itself (remember again arrays start with 0, so the second piece of the array has a 1 value). $headline[0] will echo out ‘h1′, ‘h2′, or ‘h3′, depending on the random selection.

Once they’re rotating, how do I actually track performance?

Cool, now we’ve got a few headlines out there rotating to our customers. It’s time to actually track which ones are leading to clicks and sales, which is where our tracking link comes in. On your page, at some point you’re going to link to the affiliate offer, which very basically would look like this

<a href="">This is my affiliate link</a>

We’re going to change that link to this

<a href="<? echo $headline[0] ?>">This is my affiliate link.</a>

This is going to be the outbound tracking link you use on your call to action buttons, links, etc. You’ll see that we’re adding ?h= to the end of our URL…this will pass the subid for the headline (h1, h2, h3) to our redirect link. Now we have to build out the redirect.php so our customers get rerouted to the offer with the conversion data we’re testing for. The redirect.php file will look like

$subid = $_GET['h'];
$go = ''.$subid.'';
header('Location: '.$go.'');

This one is nice and easy.

The $subid : Here we’re just pulling the ?h= from the landing page.

The $go : Now we build out our tracking link, which is just our affiliate link from before but now with $subid attached to the subid portion of the URL. Most affiliate networks have similar subid structure, either subid, s1, sub1, etc.

The header redirect : Once we have our affiliate link populated with a subid, we’re all good to send them off to the offer!

See, it wasn’t that hard was it? A few lines of code and you’re now testing multiple headlines (or images, or colors, or anything) and tracking which ones lead to clicks and sales. You can even compare CTR on the headlines very crudely by simply looking at how many clicks each subid receives in the affiliate network.

Once you understand the core concept of the tracking link, building out other elements of the tracker aren’t nearly as daunting as they might seem. Prosper202 and other trackers largely rely on what we just did – setting a variable to test and then tracking it via subid. In the exact same way you can rotate and test landing pages, offers, traffic sources, ad copy, and anything else you want to follow. The real fun comes when you want to compile all of the data and interface it for reporting.

As always, if there are holes in my code or things that could be more efficient, please comment so I can update.

Things I’ve Learned From Baller Affiliate Marketers

While many key principles to running my businesses have come through testing, trial/error and self-realization, there are a lot of things I’ve learned from the most successful people in the space (many who have gone on to bigger things). I’d like to share a few of those principles I’ve picked up over the past 7 years. While most of this is oriented to affiliate marketing, the principles can be applied to other businesses online and off.

1) If You Need It – Buy It

This is a principle I picked up early in my affiliate business and I’m glad I did. I had been working on my own affiliate campaigns for almost a year and then started working with a parter that had a couple more years experience than me. We knew exactly the campaign that we were going to run together, so we went through the process of setting up a corporation, buying domains, getting hosting, affiliate accounts, etc. When we got to the hosting portion of everything he said something like “Ok, we have a call with Rackspace and they’re going to manage our server.” Sounded fine by me. After a call with Rackspace, I find out the server cost $650/month. Having paid $10-50/month hosting up until that point, my mind was blown. I asked my partner “Do we really need to spend that much on hosting? I’m sure we could find a nice server for $100/mo and scale up as we need it.” The response was something like, “We’re planning on making hundreds of thousands of dollars with this, why would we be cheap with our server? The extra revenue we get from clicks that the server doesn’t miss will make up for the cost in a couple days. If it’s something that’s going to help your business make more money, buy it, no matter what it costs.

It’s something that immediately stuck with me and still has. That next week I threw out my laptop and spent $5k on a kickass computer with dual 30″ displays…immediately helped productivity and multitasking. If you’re already a frugal person it makes it even more difficult because I know what it can feel like to say “Do I really need to spend $300 on a better printer?” But when your goal is to run a high profit business, a few thousand on supplies is nothing in comparison to the return you’ll get from it. In addition to the physical productivity that came from juicing up my workstation, I mentally felt badass, “Look at this legit setup…I’m on another level now.” It sounds silly but the increased motivation/productivity from an invigorated mentality can’t be measured in dollars and if it can – it’s certainly worth more than the few thousand it took to buy it.

Next time you’re at BestBuy, don’t buy the horrid $30 mini-bluetooth headset that will make you feel like you’re in the Sahara desert making a phone call…get the Jawbone.

2) Always Look For Scale

Especially in the affiliate space, we know that good things don’t last. The campaign that you think you’re going to retire on is sure to plummet in the next few months. For that reason, it’s always important to assess the scalability of a campaign/project before pouring more of your resources into it.

While Numero Uno is always making sure you can take care of yourself and your family living happy and debt-free, don’t look for affiliate campaigns with the goal of making $100/day. While everyone’s benchmark is different, I like to see the potential for at least scaling to $1,000 profit/day on a campaign. If I work on something for a couple weeks and it’s up and down but there’s no steady increase in overall revenue…scrap it, or if it’s profitable let it run on autopilot and move on.

That’s not to say that lower scale higher margin projects aren’t worth testing and aren’t fun to mess around with, but don’t let it affect too much of your time during the day where you could be working on the big scale projects. It’s a common thing I’ve seen with the more successful people I know…they’ll immediately shoot down otherwise good ideas if they can’t see it scaling to $10k/day.

Think big.

3) Get Things Up FAST

I got to work in a corporate environment a little bit over the past year and while it was technically still a startup, I could see how painfully slow things move as they become more bureaucratic. Good ideas either get lost in translation or are abandoned because there are too many hoops to jump through.

Which is quite contrary to a great skill I’ve seen in my peers that’s rubbed off on me – get things up quick, because why not? If there’s a good campaign idea in your head, why would you think about it for a day, read blog posts about it, Google articles related to the idea, dissect every single similar site to make sure yours incorporates all elements? For an affiliate, launching and testing a campaign takes a couple hours (assuming you listened to me and know how to design/code things for yourself). More often than not it’s either fear or general laziness that prevents you from testing an idea spur of the moment, every time. Just get the idea up and testing and worry about perfecting it after you’ve proven the model generates revenue.

This can also be applied to full products, not simple affiliate campaigns. Have a cool infoproduct idea you think will kill it? Design the sales page in a few hours (or couple days), create the credit card submit page and then say “Sorry, we just ran out of stock! Your card was not charged and we’ll notify you when things come back!” when you make a “sale”. You’ll spend $1,000 and find out if your product has potential to make sales in a couple days rather than taking a month to fully build out the product, invest 10x as much capital, figure out customer support, fulfillment channels, etc.

Not only with launching websites and campaigns, making quick decisions is an important skill to have in any business. The most savvy guys I know are incredibly fast at judging a situation and making snap decisions one after the other.

4) Stay Under the Radar

“The loudest one in the room is the weakest one in the room.” — my man Denzel Washington said something similar to that in American Gangster.

While I’ve blatantly violated that by making a public blog where I post personal earnings, there are many things I would have loved to blog about but didn’t. Especially when you hit success on your first big campaign, it’s hard to contain your excitement. You want to tell your online buddies about it, you want to post on forums about it where people helped you, you want to blog about it (oops)…shut up about it.

The biggest affiliates out there are unnamed/unknown to most people outside of their ring, and that’s because they want it that way. Driving any sort of public notoriety to yourself will always bring attention from people asking “So what’s he running? How’s he making this money?” While 9/10 of these people are just jealous cronies that wouldn’t do anything with your campaign even if they did discover it, all it takes is 1 guy outbidding you to take thousands away from your income.

Those are a few things off the top of my head that I’ve mainly learned from others…I’ll jot down any more that pop in and maybe will write a Part 2 when I have 3-4 more.

Thanks for reading!

Affiliate Hacks #2 – Writing a PHP Cloaker

In the next little coding tutorial, I’m going to show you how to set up a basic PHP cloaker for your landing pages/offers.

What Is An Affiliate Cloaker?

Say that there’s somebody you don’t want seeing your landing pages. A cloaker will find that person and redirect them to your “cloaked” page. This cloaked page can be a different landing page (one you don’t actually use), a different website (so maybe direct linking to the offer), or any message you want (“Hahaha I cloaked you!”).

How Does This Work?

There are a few different ways to write a cloaker, the way I’m going to show you today is a very common method called IP cloaking with the programming language PHP (so PHP must be installed on your webserver). If you’re not sure that your server has PHP installed, login to any one of your websites and create a file called ‘test.php’. In this test file copy/paste the following code:

<?php phpinfo(); ?>

Now visit test.php in your browser. If a bunch of information comes up, you have PHP installed. If not, you don’t.

Back to how it works…the cloaker is based off of a tracking link you create. So you would buy a domain like, and on that domain you’d host all of your tracking links. Your tracking link redirects to your landing page, so when creating ads you use your tracking link for the ad destination URL. Instead of your ads linking to, they now link to That php link redirects to your landing page.

The cloaker code is placed on your landing page and says “If a person hits this page through my tracking link (directly from my ad), show them the landing page. If not, redirect them to my cloaked URL.” I’ll explain more about how this works when actually showing you the code.

Why Use A Cloaker?

There are more sinister reasons for cloaking which I won’t go into, but IP cloaking is a somewhat effective way of blocking affiliates from spying on your pages. If an affiliate is able to find your landing page link through a number of spying tools and tries to visit your page, they’ll be redirected. Note that many spy tools actually grab your tracking link, and many affiliates will find your ads and click on them directly – the basic IP cloak doesn’t prevent that.

How It’s Done

Now for the nitty gritty. This all starts with creating a MySQL database on your server. Here’s a basic tutorial for creating a MySQL database and table on your server.

For the tutorials sake I’m going to keep things as simple as possible. In our example we’ll use the following information:

Database name – test_db
Database username – test_user
Database password – cloaking

In that database, make a table called ‘ips’, and give that table 2 columns called ‘ip’ and ‘timestamp’. The IP can be type varchar, and the timestamp must be type DATETIME. This database stores our IP data which helps us determine who to cloak, and who to let through.

Now that we have our database set up, the first step is writing code for the tracking link. Your should contain the following code:


$db = new PDO('mysql:host=localhost;dbname=test_db;charset=utf8', 'test_user', 'cloaking');
$q = $db->prepare("INSERT INTO ips (ip, timestamp) VALUES ('$ip', NOW())");


An explanation of what’s going on here:

Line 1 – gets the users IP address and sets it to the variable $ip so that whenever we need to use their IP, we just call that variable

Line 2 – makes the connection to your database using PDO. PDO is a secure way of connecting to databases that prevents a MySQL injection and access to your server. To briefly read why you should connect using this method, click here.

Line 3 – builds the query for taking the persons IP along with the current time and popping it into your database

Line 4 – performs the task of adding the IP and current time into your database

Line 5 – sends the person off to your landing page

Yayy, your first cool tracking link is now made. Next is the actual cloaker. This code goes as the very top of your landing page, above the opening body tag:


$wl = array("12.345.67.890");
$bl = array("123.456.789.0", "98.765.432.10");

//Cloak em
$db = new PDO('mysql:host=localhost;dbname=test_db;charset=utf8', 'test_user', 'cloaking');
$result = $db->prepare($q); 
$r = $result->fetchColumn();

if (in_array($ip, $bl)) {
else if ($r >= 1){}
else if (in_array($ip, $wl)) {}
else { 

A breakdown of what’s going on here:

Line 1 – once again we get their IP and set it to a variable.

Line 2 – build out a “white list” of IPs. If there are any IP addresses you never want to cloak, put them in this PHP array. Typically, you’ll only put your IP address here so that you can build/test your landing pages and not have to worry about cloaking yourself.

Line 3 – alternatively, you can build a “black list” of IP addresses; people you always want to cloak. For instance if you’re able to sniff out the IP address of different affiliates, you can blacklist them so that even if they go through your tracking link, they’ll be cloaked by default.

Line 4 – again we make a connection to our cloak database.

Line 5 – this determines if we cloak or not. This checks (or queries) your database and says “Select from our database where the IP address generated at the top of the landing page matches an IP address found in the database (meaning the person first came through your tracking link).” The “INTERVAL 1 MINUTE” stuff means the person just came through your tracking link. That means if this person goes through your tracking link, hits the landing page, fills out an offer, and any time 1 MINUTE after that action they try to go back to the landing page, they’ll be cloaked. That’s why we include a timestamp in our database.

Lines 6,7,8 – this executes the query and grabs the rows that satisfy the criteria (matching IP address within a 2 minute timeframe).

Line 9 (first if statement) – this looks at your blacklist array. If the persons $ip is in that array, we cloak them by default.

Line 10 – if our query returns an IP address (meaning they’ve come through the tracking link just now), do nothing (show them the landing page).

Line 11 – if the IP is within our whitelist, also do nothing and show them the page.

Line 12 – if our query returns a blank result (no matches), we cloak them.

Like I’ve said, this is not the only way to cloak using PHP, and there are other ways to cloak using things like Javascript. But this gives you a very fundamental idea of what cloaking is, and how to implement it rather easily.

Also, I do not claim to be a programming expert. If there are cleaner ways to write the cloak listed above, feel free to drop a comment or e-mail me and I’ll make an update! I always love learning new information.

Pre-Live Checklist – What To Do Before Launching a Campaign

To me, there’s almost nothing worse than getting pumped about a campaign, launching it, and checking stats after an hour to see you’ve burned $100 and gotten 0 leads. You freak out and login to your accounts and find out you’ve made a stupid mistake with your traffic source or landing page. I’m going to map out some of those most common stupid mistakes in campaign setup, and it’d be wise for you to build a checklist out of it that you run through right before you’re about to set a campaign live.

1. Test the Entire Conversion Path

This means login to every traffic network you’re running, copy the destination URL in the ad, paste it into your browser and press enter. First, make sure the click goes through to your landing page (or the offer). Login to your tracker or the affiliate network and make sure the click was registered. Then click to the offer and make sure that click registered. Complete the lead and make sure the conversion pixel fired on your tracker and in the network. If the conversion didn’t fire in the network, it may have been because they blocked your IP from leads – your affiliate manager will still be able to tell you if a lead went through.

2. Check, Double-check, Triple-check Your Daily Budget

Adding an extra 0 on to your daily budget can be extremely painful – this has happened to me multiple times. A $100 test budget turns into $1,000. Always login to your traffic source and be paranoid with checking your daily budgets. In some traffic networks you can set multiple budgets on the Line Item, Campaign, & Ad Group/Creative. For test budgets, set the overall lifetime budget to the same as your campaign daily budget, and if you’re running only 1 ad group set that budget as well. It’s redundant, but you want to be as sure as possible that you don’t blow your budget.

3. Check Campaign Geo-Targeting

Make sure your campaign is geo-targeted properly. Easy way to burn money right there, especially if you’re running the same campaign over multiple geos. I actually had this happen with a dating campaign last week…I copied a US campaign over to AU and forgot to change the geotargeting. Luckily I remembered before the daypart set the campaign live, but I should have double-checked right after I finished copying the campaign.

4. Check All Rotation Variations

Are you split testing multiple landing pages or offers? If so, take Check #1 and repeat it for every variation. Copy/paste your destination URL into your browser 10 times to ensure that all of the pages are rotating in properly and that they all click through.

5. Check Your Bids

Like with adding an extra 0 onto a budget, you can accidentally set a $0.10 bid to $1.00, leading to devastating consequences. Go in and make sure all of your CPM/CPC bids are accurate.

6. Re-read Your Copy

Read all of your ads and landing page content. Make sure there are no typos or glaring errors that would detract a user from trusting your site.

7. Browser Check Your Code (Dinosaur Compatible)

Make sure your landing page works in ALL browsers. We techies often use the latest version of Chrome or Firefox, forgetting that 90% of the people in our 45+ mature dating campaign use IE7. I have every browser downloaded and self-test in them, and then use NetRenderer to check older versions of IE (the most important thing). IE needs to crawl into a hole and bleed out, for real.

8. Make Sure Your Cloaker Works

If you’re using a cloaker, make sure it’s working properly. Visit your landing page URL without going through your tracking link and make sure it redirects to the cloaked URL. If you’re using a custom cloaker, hardcode your IP into the blacklist and run through your tracking link – make sure you’re redirected. I’ve accidentally cloaked all of my real visitors before – doh.

9. Check Frequency Capping

More typically used with CPM/CPV campaigns, double check what your frequency cap is and that it’s set in the first place. If you don’t have frequency capping enabled, you’ll completely burn your CPMs on the same visitors that aren’t clicking your ads. Typically I’ll use a 1/12hr or 1/24hr frequency cap.

Going through the above list before every campaign launch should be good validation that the campaign is in fact ready to go live. If there are any checks that I’ve missed, please leave them as a comment so I can update the post!

An Argument for Insourcing

A common philosophy thrown around the affiliate space goes something like:

You can outsource most of the leg work in your affiliate campaigns, giving you more time to focus on overall strategy & traffic sources. Things like landing page design, landing page coding, API integrations, and other “busy work” can all be done by a virtual team of Indians on oDesk for $20/hr total. There’s no reason to learn how to do these things when you can pay somebody else to do it for you.

I know a lot of affiliates who have used that strategy and are successful (never learning how to design/code/handle logic/etc), but I think they could have had more success if they took a step back in the beginning and taught themselves every aspect to running a campaign.

Now, I’m not saying that outsourcing work like this is always a bad idea, because at a certain point in any business you have to outsource in order to continually grow. And when you’ve got campaigns cruising with money in the bank, you’re not going to want to waste 3 hours building landing pages. But let me switch industry-gears for a quick second to help make my point when it comes to new affiliates or entrepreneurs coming into the game.

Mark Zuckerberg. Bill Gates. Steve Wozniak. Karl Benz. Pretty much any creator of an innovative product. None of these guys got into their industries with the strategy “Wow, this is a great idea. Let me piece together a team of people who can build this prototype and eventual product.” They were passionate about their industries and taught themselves how to build their product from the ground up – nearly every aspect.

I think a big reason why they all became so successful was because having the knowledge to execute every aspect of the business altered their creativity. Facebook wouldn’t have been the same if Mark Zuckerberg thought of the idea in his head and then hired a bunch of cheap laborers to code it up. I’m sure there were dozens of moments when writing his code he stopped mid-line and thought “Wait, why would I do it this way? If I do it that way, I can add this new feature in.” His creativity was inspired by his passion and all-encompassing skill set – and that’s what made Facebook, Facebook.

That leads to another point: would Facebook have been the same if Mark didn’t know how to code and instead pieced together his team, worked with them to develop and create the idea, and then relied on them all to execute in unison? Doubtful. He had an idea, it popped into his head, and he immediately started coding it. That avoided the process of building the outsourced team which may have resulted in ideas being lost in translation or simply forgotten because he couldn’t act on it in the moment. It’s not rocket science that creativity inspires innovation, but knowledge often inspires creativity.

How does this relate to affiliate marketing? I mean, you’re not looking to build the first flying car or innovative product…you’re just looking to run some crappy affiliate offers and make a profit. But having the mindset of being passionate about innovating is what gives the top affiliates an advantage in the space. Affiliate marketing appears to be a somewhat simple and easy dream job, make money hammering away at a laptop from the beach. Once you actually start testing your campaigns, you’ll realize it’s not all it’s cracked up to be most of the time. I can’t count the number of times I’ve seen an ad repeatedly, copied the ad & landing page, gone to a network to get the offer, and then ran it only to lose a few thousand dollars. To a lot of new affiliates, that $2,000 can be 100% of your investment capital and can completely discourage (or disable) you from pressing on. How do you avoid that mistake? Innovate your campaigns. Come up with more creative ad copy. Connect with the user on your landing page more effectively. Find unique affiliate offers that you can leverage the same audience on but see a higher conversion rate.

It’s the innovative creativity that will lead all of those optimization ideas to you naturally. You can come up with catchy taglines and have your designer plug them into a page easily, but you may come up with a more creative tagline if you’re actually in Photoshop watching the words/typeface flow into the page. And it may be that extra ounce of creativity that pushes your campaign profitable.

This is something I’ve slowly learned over the years and in the past 6 months have put the effect into full-throttle. It’s also the direction I’m going to be taking this blog – not helping you learn how to outsource – but helping you learn how to insource so that you can build every aspect of your campaign. Not only will it help your affiliate campaigns, but it just may give you that next innovative idea that you’ll be able to execute on in the moment.

Page 1 of 61 12345...»