advertisement

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.
[mysql]
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`)
)
[/mysql]
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
DEFINE ('DB_USER', 'USERNAME'); // The username for your database.
DEFINE ('DB_PASSWORD', 'PASSWORD'); // The password for your database.
DEFINE ('DB_HOST', 'localhost'); // The host for your database (stays the same 99% of the time)
DEFINE ('DB_NAME', 'NAME'); // The actual name of the database its self.

$dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error());

@mysql_select_db (DB_NAME) OR die('Could not select the database: ' . 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.

// Split our URL into bits.
$url = explode("/",$ref);

// Take the 3rd part of the url (the main site)
$surl = $url[2];

// Check to see if it contains the www. at the begining
$found = ereg('\www.',$surl);

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'";
$result = mysql_query($query);
$num = mysql_num_rows($result);

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) {
	$site = mysql_fetch_array($result, MYSQL_ASSOC);
	
	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'";
			$result = mysql_query($query);
		
		}
	}

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 {

	if (!empty($surl)) {
		$query = "INSERT INTO referers (website, hits) VALUES ('$url', '1')";
		$result = mysql_query($query);
	}

}

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.
$result = mysql_query($query);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
	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.
$url = explode("/",$ref);

// Take the 3rd part of the url (the main site)
$surl = $url[2];

// Check to see if it contains the www. at the begining
$found = ereg('\www.',$surl);

if ($found) {

	$url = $surl;

} else {

	$url = 'www.'.$surl;

}

$query = "SELECT website, hits FROM referers WHERE website = '$url'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
	
if ($num == 1) {
	$site = mysql_fetch_array($result, MYSQL_ASSOC);
	
	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'";
			$result = mysql_query($query);
		
		}
	}
	
} else {

	if (!empty($surl)) {
		$query = "INSERT INTO referers (website, hits) VALUES ('$url', '1')";
		$result = mysql_query($query);
	}

}

$query = "SELECT * FROM referers ORDER BY hits DESC LIMIT 10"; // Change the limit to the top XX that you want to show.
$result = mysql_query($query);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
	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

advertisement