Take the 2-minute tour ×

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?

share|improve this question

4 Answers 4

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

share|improve this answer

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';
share|improve this answer
+1 didn't know that! –  Pekka 웃 Dec 24 '09 at 0:41

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.

share|improve this answer

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');
share|improve this answer

Your Answer


