« Creating a USB Flash Drive System Recovery System |
JavaScript Validation for HTML Forms »
Hiding Links With PHP and Counting Clicks with MySQL
There are many reasons why one might want to hide their links – perhaps you are are an affiliate marketer, the link is really long and dirty or you are simply wanting to implement a system that counts how many times a certain link is clicked (more on that later).
Affiliate marketers like to make their links appear to be on their site and handle the redirection themselves, it improves the overall trustworthiness and cleanliness of the site in general. In keeping with the clean URLs process, though I’m not sure if this really counts, you may want to clean up a link for whatever reason. The last reason I can think of, and the most useful, is that you what to implement a system to manage your links and count them at the same time. This can be a valuable tool in any online marketing campaign as you try to feel out what works on your sites. First off, we are going to need a PHP script to send all of our link requests to. For this example, we will create a script at the root of our domain called redirect.php. The following is the first bit of code that will handle the actual redirection for the links, for our example it will redirect to Google, Yahoo and Wikipedia:
<?php
$id = $_GET['id'];
$links = array(
"google" => "http://google.com",
"yahoo" => "http://yahoo.com",
"wikipedia" => "http://wikipedia.org"
);
header("Location:".$links[$id]);
exit;
?>
Now we can use the following links to get to our specified locations:
- Google
http://studge.com/testbed/redirect.php?id=google - Yahoo!
http://studge.com/testbed/redirect.php?id=yahoo - Wikipedia
http://studge.com/testbed/redirect.php?id=wikipedia
Now we can also set up a system to count how many clicks our new links are getting. I am going to use a MySQL database for this feature. I will need to set up the following table:
CREATE TABLE `linkcount` (
`id` VARCHAR( 50 ) NOT NULL ,
`count` INT( 10 ) NOT NULL default '0' ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM ;
We are going to edit the redirection code to access the database and create an entry for the link if it does not already exist. Then we will increment the count field by one each time it is called. This example uses the fictional database server mysql.example.com, using a database called database with a table called linkcount:
<?php
mysql_connect("mysql.example.com", "username", "password");
@mysql_select_db("database") or die( "Unable to connect to database");
$id = mysql_real_escape_string($_GET['id']);
$result = mysql_query("SELECT * FROM linkcount WHERE id='$id'");
if(mysql_num_rows($result) == 0) {
mysql_query("INSERT INTO linkcount (id) VALUES ('$id')")
or die(mysql_error());
mysql_query("UPDATE linkcount SET count=count+1 WHERE id='$id'")
or die(mysql_error());
} else {
mysql_query("UPDATE linkcount SET count=count+1 WHERE id='$id'")
or die(mysql_error());
}
mysql_close();
$links = array(
"google" => "http://google.com",
"yahoo" => "http://yahoo.com",
"wikipedia" => "http://wikipedia.org"
);
header("Location:".$links[$id]);
exit;
?>
That is all it takes. From here you may want to write a front-end to display your click results or you could even display the count next to the specific link in your sites navigation menu to rank the most popular outgoing links.
Edit: A follow-up has been written to this post that describes a simple script for displaying the click results: Displaying Click Counts with PHP and MySQL.
Topics: (X)HTML, MySQL, PHP, Web Development
Share: del.icio.us | digg | reddit
Very nice piece of code here, thanks so much. I’ll be blogging about it to send a few people over, I think others will find this useful too
.
Is there any chance of getting some simple code to view the stats so we don’t have to go into phpmyadmin for that?
The follow up is done: Displaying Click Counts with PHP and Mysql.
[...] Hiding Links With PHP and Counting Clicks with MySQL [...]
[...] at SuperAff.com has asked about a follow up to a previous post Hiding Links With PHP and Counting Clicks with MySQL. In this article I demonstrated how to hide links (affiliate or otherwise) and count how many times [...]
[...] Hiding Links With PHP and Counting Clicks with MySQL | Studge There are many reasons why one might want to hide their links – perhaps you are are an affiliate marketer, the link is really long and dirty or you are simply wanting to implement a system that counts how many times a certain link is clicked (more on th (tags: php seo mysql tools affiliate links) [...]
[...] has found a simple solution for cloaking affiliate links and gotten the designer to write some more code to make tracking the clicks simpler. This is [...]
[...] had quoted an article from Studge.com which gives you PHP code to cloak affiliate links as well as click tracking by using MySQL database [...]
[...] My personal favourite from this list is this one from Hiding Links With PHP and Counting Clicks with MySQL [...]
Hi,
i had a problem.
If someone type his own id it wil be displayed in my database but its not a valid ID.
And i’did like a default redirect (Not displayed in the database), so even if there is no ?id= in the url.
Can you please help me.
Niels Harland
(Sorry for the bad English)
Solution is below…
Niels, your problem is easily solved – first, you would need to manually create the database rows for Google, Yahoo! and Wikipedia in the
linkcounttable. Then edit the following bit of code:if(mysql_num_rows($result) == 0) { mysql_query("INSERT INTO linkcount (id) VALUES ('$id')") or die(mysql_error()); mysql_query("UPDATE linkcount SET count=count+1 WHERE id='$id'") or die(mysql_error()); } else { mysql_query("UPDATE linkcount SET count=count+1 WHERE id='$id'") or die(mysql_error()); }to this:
if(mysql_num_rows($result) == 0) { header("Location: http://example.com/invalid-link.php"); exit; } else { mysql_query("UPDATE linkcount SET count=count+1 WHERE id='$id'") or die(mysql_error()); }You will need to create some sort of
invalid-link.phppage that will serve as the default landing page for bad?id=requests.[...] so good I decided to write a quick follow up to let you all know too. Firstly a guy over at http://studge.com/hiding-links-with-php-and-counting-clicks-with-mysql/ has made a superb and very easy to follow guide on cloaking links using php while being able to [...]
i couldn’t find anything on german websites and i took me a long time to find this tutorial. great job and thank you very much. i also have some sites, where i like to hide the affiliate-links. your script even counts the clicks. again: well done.
RE mysql_connect(“mysql.example.com”
Can you translate that syntax into form which has
$database['host'] = ‘localhost’;
$database['username'] = ‘uname’;
$database['password'] = ‘upw’;
at http://domain.com
I would like to try it out.
Thanks for the great script. I’m going to do a cashback shopping site. I am also wondering how to track whether a member (registered user) actually makes a purchase after clicking my affiliate link. Because I plan to give some cash back to members when they make a purchase through my link.
I am wondering how to track who makes a purchase at what time? You don’t need to give the script, I only need to know ‘how’.
Thank you so much!
I wouldn’t know how to do something like that. After the customer clicks your affiliate link, they would generally be directed to a server other than your own – making it virtually impossible to run any further code on the transaction.
This post is definitely worth a comment. Do you have any idea how long I have been looking for a code like this??! I am thinking there must be a way to add the referrer to this code too. This way you could get a click count, and see where that click came from. I’ll be bookmarking this page and checking back. Great post!!
Great code, although it doesn’t seem to work with affiliate future’s links which start with http://scripts.affiliatefuture.com/AFClick.asp?affiliateID
any suggestions on how I can make it work? It just stops at af’s homepage?
Have you tried running that link on its own? It is likely processing the affiliate ID number and then dumping the user at their main page with a cookie set on the user’s system to notify their server that you directed them to the site.
I have tested this method with URLs that are passing variables and it works just fine.
How can you make this work with several products,without adding each one by hand?
great script
Did work for us too. Thanks!
Very clean code, thanks a bunch!
uh oh. this is VERY BAD. if you run a directory or some link exchange website than this will actually do no good to the websites you are linking to and it can even harm you
As far as Google is concerned (or any other search engine) you are not pointing to any particular website with these links but rather to a page with no content (as your redirect.php generates no output). Therefore, these links will not be considered neither outbound links nor inbound links. In what regards the search engines, you have a lot of links pointing nowhere…
But, the solution is quite simple and you won’t have to scrap all your code
Before the line
header(“Location:”.$links[$id]);
add
header( “HTTP/1.1 301 Moved Permanently” );
And ta-da, your links are all SEO friendly.
Now, because I was useful, please visit my php relate blog at Zebra PHP Components Framework” and my Do-it yourself Internet promotion website
Hi Stephan,
Thanks for adding to this awesome code and Studge thanks for sharing!!
I have tried your suggestion but can’t get it to work. I have changed to code to read:
—————
“wikipedia” => “http://wikipedia.org”
);
header( “HTTP/1.1 301 Moved Permanently” );
header(“Location:”.$links[$id]);
exit;
?>
—————
What have I missed?
Thanks
Fred
Is there a similar script that will support links stored in MySQL that are displayed on pages via a php echo from a recordset? Each link is in it’s own record along with the affiliate name.
thx,
Dave
[...] Redirect Scripts (if you love codes try Studge) [...]
If this could be made into a wordpress plugin, it would be of very great help for non-coders out here. Anyone up for the challenge?
[...] counts all the links together. I am not that good at PHP, but the code I used can be found here:rrhttp://studge.com/hiding-links-with-php-and-counting-clicks-with-mysql/rrYou can use the above code or not, your choice.rrI want the clicks displayed in a graph, you can [...]
Hey, thank you, but in the meantime it could be solved easier, isn´t it? Especially if you you use a Wordpressinstallation combined with the widget solving this.
It sure could, this is merely a how-to for someone writing custom code or not using a CMS.
Thanks! Came up 2nd result on google when searching “php redirect script count clicks” this is exactly what I needed.
Thank you for this great script! This is what I need!
I may have missed this, but is it possible to tweak the code to have it count only unique clicks? I’d like to use the script to power a number of “Like” buttons on our pages, but I don’t want people to be able to artificially drive up the scores.
I’m not sure of how affiliate links work but the php code here basically puts a link inside the url bar of your browser. i.e the link that you click on will say http://www.mydomain.com/advert.php?ad=1 and then when you click it the browser url will show http://www.someaffiliateprogram.com/affid=12345. If the user wants to remove this all he really needs to do is remove the affid=12345 in the url and hit enter. If i’m mistaken can someone please set me straight.
Thanks
Clinton
I think I understand what you are saying here. When the affiliate link is followed, it should set a cookie that shows my affiliate code has brought this user to their site – the cookie lasts a set amount of time and any purchases made during this period would yield me a percentage (this is just an example of a typical affiliate system). After the link is already followed, it doesn’t really matter what the user puts in the address bar since the cookie has been set.
thanks for the clear explanation you are awesome!
The lastet update is that google can follow links over php header links.
On one of my websites i have just changed my redirect script that i have used over years to a javascript version loaded inside a noindex, nofollow page.
the linkedsite.com will get backlink juice…
now..
Redirect to
<!–
window.location = "http://”;
//–>
Going to give it a try. Thanks for the howto.
thanks for you advice and your share