Track Referers with PHP
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