php - unique visitor count not working with cookies
问题描述
I am Beginner and want to learn how to count unique visitors by using PHP cookies. I tried to write this code. And also I am storing it in a database. The problem is I am not getting real visitors only 2-3 visitors came on this page according to google analytics, but according to my code, I am getting 50. this error is because of google bots?
I think the problem is in my code please help me to fix this.
Here is my code
<?php
include 'configuration.php';
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
if (preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-perl|facebookexternalhit/i', $_SERVER['HTTP_USER_AGENT'])) {
// is bot
}else{
$value = bin2hex(random_bytes(10));
$path = "/";
$expires = time()+15780000;//6 month
$cookie = '1';
if (!isset($_COOKIE['Q_zWnE8_aq']))
{
$name= 'Q_zWnE8_aq';
$new_visitor = $cookie++;
setcookie($name, $value,$expires,$path,"mydomain.in");
$sql010 = $conn2->prepare("SELECT * FROM unique_vistor WHERE ip = ? ");
$sql010->bind_param("s",$ip);
$sql010->execute();
$reS = $sql010->get_result()->fetch_all(MYSQLI_ASSOC);
if(count($reS )>0){
// already exists
}else{
$result55=$conn2->prepare("INSERT INTO unique_vistor(id,name,value,expires,new_visitor,ip) VALUES (?,?,?,?,?,?)");
$result55->bind_param("isssss",$id,$name,$value,$expires,$new_visitor,$ip);
$result55->execute();
$result55->close();
}
}
}
?>
解决方案
我在 StackOverflow 上发现了如何检测机器人,我已经更新了上面的代码,请告诉我。这是正确的方式吗?
if (preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-perl|facebookexternalhit/i', $_SERVER['HTTP_USER_AGENT'])) {
// is bot
}
推荐阅读
- algorithm - 排列数组中的数字以使所有负值出现在所有正值之前,最少需要多少次交换?
- angular - Angular 是否支持递归嵌套动态组件?
- sql - 使用第一个表中的两个不同列查询以连接两个表
- android - Android 本地 VPN - 过滤 URL
- python - 在另一个函数中使用一个函数的返回结果
- android - 在将另一个项目用作android中的库后,黄油刀在我现有的项目中不起作用
- asp.net - Axios 在 POST 上抛出网络错误
- python-3.x - Scipy插值三次样条边界
- swift - 二元运算符“+”不能应用于“T”和“U”类型的操作数
- django - 无法通过“模型”实例 django 访问管理器