My Stuff
Username

Password

Articles/Snippets
ASP Classic
C
C#
C++
CSS
HTML
Java
Javascript
MySQL
Perl
PHP
Python
Ruby
Unix/Linux/BSD
VB 6
VB.NET


Track Referers with PHP


Your rating: None Average: 4 (1 vote)

There's a lot of software out there which tracks referers, but that just isn't as exciting as making our own.

There is a Server variable in PHP named HTTP_REFERER. This variable holds the url of the page the user clicked to get to the current page.

This example will write referers, destination, and timestamp to a MySQL database which did not come from the current domain.

The first step is to create a table in your database for this. Below is the schema:

CREATE TABLE `referer` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`timestamp` TIMESTAMP NOT NULL,
`referer` VARCHAR(255) NOT NULL,
`destination` VARCHAR(255) NOT NULL
);

Now all we have to do is insert the logic to the top of the page we want to monitor. Since we also log the destination, this script would be useful to place in a header include file which could log the referers to any page of your site.

<?
// set your domain
$mydomain = "mydomain.com";
 
// only log if the referer isn't this domain
if( strstr(!$_SERVER['HTTP_REFERER'],$mydomain)
{
  // insert record
  $result = mysql_query("INSERT INTO referer (referer,destination) VALUES('" . $_SERVER['HTTP_REFERER'] . "','" . $_SERVER['PHP_SELF'] . "')";
}
?>

Now you can get creative with how you want to view and what you want to do with that data.

Happy Logging!

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can use BBCode tags in the text.
  • You can enable syntax highlighting of source code with the following tags: [code], [blockcode], [asp], [awk], [c], [cpp], [csharp], [drupal5], [drupal6], [java], [javascript], [jquery], [mysql], [perl], [perl6], [php], [python], [ruby], [sql], [vb], [vbnet], [xml].
  • Use to create page breaks.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.