首页 > 解决方案 > 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();
            
        
    }

  }
}
        ?>

标签: phpmysqlcookiesip-address

解决方案


我在 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
}

推荐阅读