Skip to content Skip to sidebar Skip to footer

Http_referer Not Working On Javascript Src

Scenario: I want to detect from which website my visitors are coming from an javacript SRC. Visitor from google.com ----> My Website(Detect if visitor come from google)

Solution 1:

The problem is that the referer of the script is the page that includes the script. Not the page you came from before getting to that page.

What you could do is:

<scripttype="text/javascript"src="ref.php?referer=<?phpecho urlencode($_SERVER['HTTP_REFERER']);
?>"></script>

Then you have free access to $_GET['referer'] instead of $_SERVER['HTTP_REFERER'] inside ref.php :)

Solution 2:

This is a pure javascript solution, as you asked for it

(document.referrer.match(/^https?:\/\/([^\/]+\.)?google\.com(\/|$)/i))
    ? document.write("\<scriptsrc='http://domain/hello-google.js'type='text/javascript'>\<\/script>"); 
    : document.write("\<scriptsrc='http://domain/hello-kitty.js'type='text/javascript'>\<\/script>");

1st UPDATE

Well, if you want to do it from a PHP file or snippet, then you can do it this way

<scripttype="text/javascript"src="
<?phpif (preg_match('/^https?:\/\/([^\/]+\.)?google\.com(\/|$)/', $_SERVER['HTTP_REFERER'])){
    echo"http://domain/hello-google.js"; 
}else{
    echo"http://domain/hello-kitty.js"; 
}   
?>"></script>

I believe you want to load a different .js file depending on referrer but not redirecting to a .js file since It doesn't make any sense.

2nd UPDATE

Just another silly thing; somehow I believe you just put my snippet into your ref.php but it won't work that way - since you're including PHP file your first line (the javascript directive) should look like this

<scripttype="text/javascript"src="<?phpinclude('ref.php'); ?>"></script>

Solution 3:

If u use mor_rewrite to redirect to your ref.php HTTP_REFERER will be NULL. If you do it, you add some code to .htaccess like this:

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !www.example.com [NC]
RewriteRule \.php$ - [F,NC]

If you use ajax, also you should send Referer header by yourself. And so on. If Referer doesn't exests, so request send without it and u should simply add Referer header by yourself

Post a Comment for "Http_referer Not Working On Javascript Src"