PHP Code

How to track referrers to your website

When running marketing campaigns, it's great to know where your visitors and customers are coming from, so that you can track conversion based on source, and determine ROI for various advertising link campaigns that you're running.

This code will capture the visitor's referring URL when they first enter your site. This could be a query string from a major search engine, it could be the URL of a website linking to yours, and you could even force it to be something specific. For example, if you want to track how many visitors are clicking on your email signature, you can use the URL

Then in any form or conversion point on your site, have a hidden field where you echo the $_SESSION['source'] variable. Then when you get the lead information, you can see where that lead came from.

//set the source of this visitor
if (!isset($_SESSION&#91;'source'&#93;)) {
	if((isset($_GET&#91;'source'&#93;))&&($_GET&#91;'source'&#93;!='')) { // ?source= in querystring, such as email sig
		$_SESSION&#91;'source'&#93; = $_GET&#91;'source'&#93;;
	} else {
		if($_SERVER&#91;'HTTP_REFERER'&#93;) { // referred from another web page
			$_SESSION&#91;'source'&#93; = $_SERVER&#91;'HTTP_REFERER'&#93;;
		} else {
			$_SESSION&#91;'source'&#93; = 'direct'; // typed directly into browser


  1. Justin,

    This is great info. Can you point me to a website where this tracking method is implemented? If I can see an example maybe I can implement this. My programming knowledge is limited.


    Paul G.

  2. We've noticed here on our end that $_SERVER['HTTP_REFERER'] sometimes gets swiped and is not a direct type in like your script is saying. Done testing and the strange thing here is that in the same browser, we can jump from one site to our site, and works, then from another site to oru site, and it doesn't. Currently searching a solution to this. Also, from what I hear, some browsers don't support HTTP_Referer. Javascript may be the only solution here however, we haven't tested this yet – this may or may not work.

Leave a Reply

Your email address will not be published. Required fields are marked *

To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image