Verify that clicks are coming from own website
I have a file go.php on my website that tracks the clicks on certain links and I want to count only the clicks that are made on my website and not on other sites that copy that link (site.com/go.php?id=). I have tried with this code
if($_SERVER[HTTP_REFERER] && !preg_match("/site\.com/", $_SERVER[HTTP_REFERER])开发者_运维知识库) {
header("Location: http:// www .site.com");
die();
}
but is not working properly, clicks from other sites are counted. Is there any way to count only the clicks made on my website?
EDIT: I formatted the code, but I left the spaces near http://
and www
. -gore
$_SERVER[HTTP_REFERER]
is not worth of considering as there is no guarantee that it will be send by the user. Also its value might be modified.
You could use quite common technique that uses unique tokens:
//some-file.php:
$uniqueToken = substr(sha1(uniqid()), 0, 8); // 8-characters long unique token, eg "2fac223a"
$_SESSION['token'] = $uniqueToken;
// ...
<a href="go.php?id=123&token=<?php echo $uniqueToken ?>">Click here</a>
//go.php:
if (!isset($_GET['token']) || $_SESSION['token'] !== $_GET['token']) {
// invalid request
exit;
}
// ...
The $_SERVER['HTTP_REFERER']
variable is, at best optional, and even user-settable, and so is not a serious source of information. It you have previously set a cookie on another page (and you may want to use browser-side cookies, not server side $_SESSION
's that can expire in a default 30 minutes) then checking for that information would tell you if they visited other pages on the site before landing on the 'go.php' page.
I think you're on to the right idea here. In my opinion, working with regexes can be kind of a pain, so perhaps this would be simpler:
<?php
//make sure to use !== rather than != with strpos
if(strpos($_SERVER['HTTP_REFERER'], 'site.com') !== false){
//if you're here, you've got a match for site.com
}
?>
I hope that's helpful.
If you want to try a different route than $_SERVER['HTTP_REFERER'] or setting cookie/session, you could write a script on the landing pages that will check the Apache access log to see if the requesting IP address was just previously visiting one of your linking pages... this should work even if they have cookies turned off or try to forge the referrer, and there's no visible url token
精彩评论