Archive for April, 2007

Using the referrer URL with a session

To make use of the referrer URL which can easily be got with a bit of PHP (like this) you can stick it in a session. Using a session you can make sure you only get the URL when people first land on your website - then store it for a set period of time:

<?php
session_start();
if(!isset($_SESSION[’referrer’])){
//get the referrer
if ($_SERVER[’HTTP_REFERER’]){
$referrer = $_SERVER[’HTTP_REFERER’];
}else{
$referrer = “unknown”;
}
//save it in a session
$_SESSION[’referrer’] = $referrer; // store session data
}
?>

First of all we check to see if the referrer URL has already been set
if(!isset($_SESSION['referrer'])){ ...
If not we set the session variable. If we can’t get the URL it gets set to “unknown” in the above example. For some reason you can’t always get the referrer URL, i’ve found that links originating from Gmail for example don’t give you a referrer URL, but yahoo does - i’m sure theres some great reason for this, but it beats me (may be its a spam security thing)

Anyway, once you’ve got a session variable set you can call it at any time until the browser window is closed or the variable runs out (theres a default time limit set in the php.ini, but you can also set it in your script - another tutorial for this bit) you’ve normally got 180 minutes as default for a session timelimit before your variable is lost.

To call your variable from another page you simply need to do this:
<?php
session_start();
echo “referrer = “. $_SESSION[’referrer’]; //retrieve data
?>

Stick that code somewhere on another page and if the first script has already been run at some point you’ll get the text “referrer = http://your.referrer.url” printed. But using the first bit of code judiciously you could also store other variables, such as landing page and also number of pages visited by incrementing a variable. Find out more here:

http://uk2.php.net/session
and this one is great too…
http://www.tizag.com/phpT/phpsessions.php