Skip to content

Instantly share code, notes, and snippets.

@qsun
Created November 11, 2011 09:22
Show Gist options
  • Save qsun/1357582 to your computer and use it in GitHub Desktop.
Save qsun/1357582 to your computer and use it in GitHub Desktop.
Real Time Referrer Indexing
<?php
//////////////////////////////
// Referreral Builder 1.0
// Copyright 2011, Russ Jones, Virante, Inc.
///////////////////////////////
// Assumes you create a table called
// ref_slots with 3 fields, url and ref, each varchar(255) and status, tinyint, REF should be primary key
$dbh = mysql_connect("localhost","username","password");
mysql_select_db("refs");
// First, find and display all "as seen on" links
$uri = $_SERVER['REQUEST_URI'];
$q = "SELECT * FROM ref_slots WHERE url='$uri' AND status=1";
$r = mysql_query($q);
if(mysql_num_rows($r)>0) {
echo "<b>As Seen On</b><ul>";
while($row = mysql_fetch_assoc($r)) {
$ref = $row['ref'];
$p = parse_url($ref);
extract($p);
echo "<li><a href='$ref'>$host</a></li>";
}
echo "</ul>";
}
// Second, let's grab the referrer and see if it needs to be added.
if(strlen($_SERVER['HTTP_REFERER'])>1) {
$ref = $_SERVER['HTTP_REFERER'];
if(isGoodRef($ref)) {
$q = "SELECT * FROM ref_slots WHERE ref='$ref' LIMIT 1";
$r = mysql_query($q);
if(mysql_num_rows($r)==0) {
$data = file_get_contents($ref);
if(!stristr($data,$uri)) { mysql_query("INSERT INTO ref_slots VALUES('$uri','$ref',2"); } else {
$c = "http://webcache.googleusercontent.com/search?q=cache:$ref+&cd=1&hl=en&ct=clnk&gl=us";
$ch = curl_init();
curl_setopt($ch,"CURLOPT_URL",$c);
curl_setopt($ch,"CURLOPT_RETURNTRANSFER",true);
curl_setopt($ch,"CURLOPT_REFERER","http://www.google.com");
curl_setopt($ch,"CURLOPT_USERAGENT","Opera/9.80 Windows NT 6.1 U en Presto/2.9.168 Version/11.50");
$data = curl_exec($ch);
if(!stristr($data,$uri)) {
mysql_query("INSERT INTO ref_slots VALUES('$uri','$ref',1)");
} else {
mysql_query("INSERT INTO ref_slots VALUES('$uri','$ref',2)");
}
}
}
}
}
// STEP 3, Let's randomly check and update 1
$rand = rand(0,100);
if($rand==1) {
$q = "SELECT * FROM slots_refs WHERE status=1 ORDER BY rand() LIMIT 1";
$r = mysql_query($q);
$n = mysql_fetch_assoc($r);
extract($r);
$ch = curl_init();
}
function isGoodRef($ref) {
$badrefs = array($_SERVER['SERVER_NAME'],"google.com","bing.com","yahoo.com","blekko.com","duckduckgo.com","facebook.com","digg.com","wikipedia.org");
foreach($badrefs as $bad) { if(stristr($ref,$bad)) { return false; }
return true;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment