views:

59

answers:

4

I was wondering if it is possible to execute a script depending on the referrer site. for example if a user accesses my site from Facebook then i want the script to be activated, but if the user accessed the site through google search then the script will not be ran. Is this possible?

+2  A: 

You should be able to test $_SERVER['HTTP_REFERER'] to see if the user came from facebook and behave differently.

mopoke
A: 

It's possible. Just bear in mind that the referer can be spoofed, so you should never do security relevant things based on its value.

Pekka
+1  A: 

Do you mean a server-side or client-side script?

From the client side you can access the referrer through document.referrer (yes, with a doubled ‘r’, even though the corresponding HTTP header is mis-spelled). eg.:

if (document.referrer.toLowerCase().indexOf('//www.example.com')) {
    document.getElementById('message').innerHTML= 'Hello, visitor from example.com';
}
bobince
+1 didn't know that!
Pekka
A: 

I would do something like this:

if (array_key_exists('HTTP_REFERER', $_SERVER) === true)
{
    // this will give you something like google.com or facebook.com
    $domain = str_ireplace('www.', '', parse_url($_SERVER['HTTP_REFERER'], 'PHP_URL_HOST'));

    // check if there is any referer script you want to execute
    if (is_file('path/to/scripts/' . $domain . '.php') === true)
    {
     // include the path/to/scripts/google.com.php for instance
     include('path/to/scripts/' . $domain . '.php');
    }
}
Alix Axel