Top Referer Script
22,857 viewsPHP Tutorials March 14th, 2007
Find out who the top 5, 10 or 15 etc... referral sites are that link to your site. Site's are listed in a MySQL database and then listed out using 1 PHP file. You can find out all about who is linking to you, and even link back to them to give credit, where credit is due!
Alright, this is going to be a non-aesthetic script, so assume that no visuals are provided with the code. We are just going to list out out the top 10 referrers for you, then you can just include it into a file for easier management.
We just need to quickly create our database, run this query in your PHPMyAdmin or whatever database program you use.
-
CREATE TABLE `referers` (
-
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
-
`website` VARCHAR(255) NOT NULL,
-
`hits` INT(11) UNSIGNED NOT NULL DEFAULT '0',
-
PRIMARY KEY (`id`)
-
)
So, as always we create our database connection script, we will include this into our referer script so that we can keep our code cleaner and just use an include instead of writing out all of our database connection info directly into the referer page.
-
<?php
-
-
$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error());
-
-
?>
The code has been commented for you to know where to put your database information. Now we create our referer script, the full code is shown at the bottom.
-
<?php
-
require('mysql_connect.php');
-
-
// Find out or base pure referer.
-
$ref = $_SERVER['HTTP_REFERER'];
This is where we get our referer, except this is the whole referral URL, we don't want that. What if the same site links to you from www.website.com/page.html and www.website.com/page2.html. We want just the www.website.com part of the URL, so that is what we do next.
This is where we select just the www.website.com part of our URL, we explode our URL and separate it at the slashes (/) and assign it to $url.
Next we need to select the part of the URL that we want, so we take the 3rd part, since we used explode, this exploded our URL into an array, and to access an array you just write what you want, ($url[0] corresponds to the first object in the array, $url[1] corresponds to the second part in the array, so on and so forth), the 3rd part of our array ($url[2] which equals the 3rd part) is the www.website.com part of the URL.
Now we use some simple regular expressions to check if the our URL so far contains the www. at the beginning, since when you link to a site you can either put, website.com and leave out the www. or www.website.com and keep it in. So we just use a simple regular expression to check if the URL has it or not.
-
if ($found) {
-
-
$url = $surl;
-
-
} else {
-
-
$url = 'www.'.$surl;
-
-
}
Now, this is where we put the www. on the beginning of the URL, so we check if our variable $found is true. By true I mean, if our regular expression turned of true or false. If it is true, just continue on, if it didn't pass the test then that means there is no www. at the beginning and we need to add it on manually.
-
$query = "SELECT website, hits FROM referers WHERE website = '$url'";
Now we create our query to check if the URL is already submitted into the database, so we make our query, execute it then use mysql_num_rows() to check how many rows are selected.
-
if ($num == 1) {
-
-
if ($site['website'] != 'www.') {
-
-
if ($site['website'] != 'www.tutorialcode.com') { // Make sure you put in YOUR website into this section.
-
-
$hits = $site['hits'] + 1;
-
$website = $site['website'];
-
-
$query = "UPDATE referers SET hits = $hits WHERE website = '$website'";
-
-
}
-
}
Now, if the number of rows selected equals one, we only want to update our hits for that specific URL and not insert it into the database again.
Now, we also don't want to submit a blank into the database, so if we are just typing the URL directly into the address bar it will be a blank URL and will come out as www. (since we add it manually) so we make an if clause, saying if it does not equal just www. then continue, and also since we don't want to add your own website as a referral make sure you input the name of your website into the commented line.
Next since we used mysql_fetch_array() onto our query results, all of our results are in an array that we can access using a variable. So we want to add 1 to the number of hits the website has sent us, so we use $site['hits'] + 1 to add one to our hits.
We use an UPDATE query to just update our hits, pretty straight forward. Then we execute our query, and close our 2 if statements, now onto the else statement for our first if.
-
} else {
-
-
$query = "INSERT INTO referers (website, hits) VALUES ('$url', '1')";
-
}
-
-
}
Now, this is where we would insert a new referer into the database, way up before we add the www. part to our URL we created a variable called $surl this was our selection of the 3rd part of our URL. So we check to make sure that it is not empty, so in other words if there actually is a referer, then we use use a simple INSERT query to insert our referer into the database.
-
$query = "SELECT * FROM referers ORDER BY hits DESC LIMIT 10"; // Change the limit to the top XX that you want to show.
-
-
echo '<a href="http://'.$row['website'].'">'.$row['website'].'</a> - <b>'.$row['hits'].'</b><br />';
-
}
-
?>
This is where we select our top 10 referers from the database, we write up our SELECT query, execute it then use a while() loop to loop out all the info, I just loop out a simple top 10 list, that shows the referer, a link back to the referer, and how many hits it has sent to your site.
Now I will just list out the full script for you -
-
<?php
-
require('mysql_connect.php');
-
-
// Find out or base pure referer.
-
$ref = $_SERVER['HTTP_REFERER'];
-
-
// Split our URL into bits.
-
-
// Take the 3rd part of the url (the main site)
-
$surl = $url[2];
-
-
// Check to see if it contains the www. at the begining
-
-
if ($found) {
-
-
$url = $surl;
-
-
} else {
-
-
$url = 'www.'.$surl;
-
-
}
-
-
$query = "SELECT website, hits FROM referers WHERE website = '$url'";
-
-
if ($num == 1) {
-
-
if ($site['website'] != 'www.') {
-
-
if ($site['website'] != 'www.tutorialcode.com') {
-
-
$hits = $site['hits'] + 1;
-
$website = $site['website'];
-
-
$query = "UPDATE referers SET hits = $hits WHERE website = '$website'";
-
-
}
-
}
-
-
} else {
-
-
$query = "INSERT INTO referers (website, hits) VALUES ('$url', '1')";
-
}
-
-
}
-
-
$query = "SELECT * FROM referers ORDER BY hits DESC LIMIT 10"; // Change the limit to the top XX that you want to show.
-
-
echo '<a href="http://'.$row['website'].'">'.$row['website'].'</a> - <b>'.$row['hits'].'</b><br />';
-
}
-
?>
Just make sure you have your mysql_connect.php file in the same directory, if you change it then you must change the path to it in the require() at the top of the file.
And that's all! If you have any questions on how to use this, or don't quite understand something. Just make sure you leave a comment, I usually answer the same day!
Thanks,
Sean
Download Source Code
Referral Script Source

(17 votes, average: 4.00 out of 5)
March 17th, 2007 at 8:33 pm
How do I get the database structure in order to try this?
March 18th, 2007 at 9:21 am
You are right, I forgot the SQL statement you need to create the table in your database!
It has been added to the top of the tutorial.
Thank you for pointing that out, Sean.
April 14th, 2007 at 4:49 am
Nice script, but it would be nice to count an IP only once per hour.
April 16th, 2007 at 9:34 pm
@JS - Ya, that is true but that is a little bit more of an advanced feature and I will maybe implement that in a later script version of this tutorial.
I might have to write a whole new tutorial for that though!
April 20th, 2007 at 2:10 am
Nice work.. I am willing to pay an amount for count an IP only once per day script!
May 30th, 2007 at 1:22 pm
can you give examples on how to use the script in a real website?
May 31st, 2007 at 7:34 am
Hey, nice script! Is there any way to block certain url's?
June 16th, 2007 at 11:40 am
When I used this script, my computer caught on fire. Where do I go to complaing?
June 21st, 2007 at 9:02 am
Complain to your computer manufacturer for giving you a faulty power supply, or to the person that manufactured your power supply.
June 21st, 2007 at 6:58 pm
In the update part, you don't need to check for blank urls and to see if it's your own website. This is only needed in the inserting part, since if you never insert it, you won't meet it in the update either.
June 21st, 2007 at 7:22 pm
It is kinda wrong to check for blank urls and your own url in the update part. That should be checked in the insert part, so those urls never get inserted.
June 22nd, 2007 at 6:08 am
It's because you had to much pressure on your computer.
And now I'm fine, I mean I know how to use this script.
July 9th, 2007 at 11:58 pm
A good one... just what im looking for... thanx
July 22nd, 2007 at 7:01 pm
[...] Click here to read more. Bookmark [...]
October 2nd, 2007 at 8:41 pm
This tutorial is great!
But, i am facing some problem, this shows my own site as a referer. How can i remove my own site? i tried removing from database but it creates again and id for my site.
Also, can i stop auto addition of site?
i just wanna add sites of my own choice and they show inhits..
thanks
December 20th, 2007 at 6:26 pm
It doesnt work for some reason will version of php matter?
March 22nd, 2008 at 10:41 am
hi,
what have I to add to my index page to use the script.
I used and the script was working, but the referer list was shown at the top of all pages.
I am not really a programmer, so I hope that you can help me!
Thx in advance.
sajos
March 23rd, 2008 at 5:15 am
the problem has been solved!!
May 21st, 2008 at 10:27 pm
VERY nice piece of software!
tnx a lot!!!
I made a few mods on your code. I wanted to store not only the referer's domain, but its full URI, including parameters. That's because some forums and sites show different content based on parameters.
For exemple, a phpBB shows different threads based on parameters sent to viewtopic.php, so not even a domain.com/viewtopic.php would be enough for me, I want domain.com//viewtopic.php?p=2050857#2050857.
Another mod I did is that I host the same blog on different domains, so I don't want do store a domain referencing another.
When I'm done I will create a post on my blog explaining everything with the codes.
There are a few things I still wanna implement. First of all, I need timestamp to be able to know when the visit happene, because I wanna list referers based on by day, by days range, by week, by month, etc. Tomorrow I'll search how I can deal with timestamp on php.
Another thing, and this one I don't know if I will be able to implement by myself. I want to separate visits from hits. Maybe using cookie I can do something about that...
The last thing I have in mind is removing me from the listings. I will try something based on cookie, so that I put a cookie on my browser and when that cookie is found the hits are not counted.
If somebody has ideas about it feel free to contact me at spf01 AT hikarinet dota info. This is a spamfilter email but it works
tnx!!!
June 6th, 2008 at 2:47 pm
I've download the script and don't know how to use the script
Please help me...
August 2nd, 2008 at 5:57 pm
hi. thx for coding. i use that for my content management system.
October 29th, 2008 at 6:00 pm
Very nice script.
Only I'm afraid that $_SERVER['HTTP_REFERER']; returns NULL in some situations. Is it possible? or this is something that works in any situation (perhaps security on visitors browser is set to high or something like that)?
March 12th, 2009 at 1:08 am
if i want to put a website on blacklist ..to not show in top referer can i? sorry for my bad english..by the way great script
December 13th, 2009 at 2:44 am
can final show website on two column ?
December 13th, 2009 at 2:45 am
can add final show website on two column ?
January 9th, 2010 at 11:22 am
good script and thanks...
March 21st, 2010 at 11:37 am
very good script ...thanks !