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
2009-12-23 23:51:45
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
2009-12-24 00:04:53
+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
2009-12-24 00:37:50
+1 didn't know that!
Pekka
2009-12-24 00:41:33
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
2009-12-24 01:58:12