Reputation: 217
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)
<script type="text/javascript" src="ref.php"></script>
refer.php
<?php
if (strstr($_SERVER['HTTP_REFERER'], 'google.com') !== false) {
header("Location: http://mywebsite.com/organic-traffic.js");
}
else {
header("Location: http://mywebsite.com/frequent-visitors.js");
}
?>
The above PHP code doesn't work. But if I use normal javascript "document.referrer" its detected.
If I access the file ref.php directly then the refer is detected also. Looks like its taking My website as referral and not google.com
Upvotes: 0
Views: 1022
Reputation: 324650
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:
<script type="text/javascript" src="ref.php?referer=<?php
echo urlencode($_SERVER['HTTP_REFERER']);
?>"></script>
Then you have free access to $_GET['referer']
instead of $_SERVER['HTTP_REFERER']
inside ref.php
:)
Upvotes: 1
Reputation: 9235
This is a pure javascript solution, as you asked for it
(document.referrer.match(/^https?:\/\/([^\/]+\.)?google\.com(\/|$)/i))
? document.write("\<script src='http://domain/hello-google.js' type='text/javascript'>\<\/script>");
: document.write("\<script src='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
<script type="text/javascript" src="
<?php
if (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
<script type="text/javascript" src="<?php include('ref.php'); ?>"></script>
Upvotes: 0
Reputation: 69
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
Upvotes: 0