PHP implements a simple visitor statistics function

1. Simple statistics of files

Use php to implement a simple visitor statistics function, and count the total number of visits to the website, which is simple and practical. PHP opens the text file every time, gets the number in the text, adds 1 and writes it into the text. Therefore, as long as there is a visit every time, the number of simple visitors will be counted by accumulating the number of PVs.

<?php
    if(!file_exists("count.txt")){
        $one_file=fopen("count.txt","w+"); //建立一个统计文本,如果不存在就创建
        echo"您是第<font color='red'><b>1</b></font>位访客"; //首次直接输出第一次
        fwrite("count.txt","1");  //把数字1写入文本
        fclose("$one_file");
     }else{ //如果不是第一次访问直接读取内容,并+1,写入更新后再显示新的访客数
        $num=file_get_contents("count.txt");
        $num++;
        file_put_contents("count.txt","$num");
        $newnum=file_get_contents("count.txt");
        echo"您是第<font color='red'><b>".$newnum."</b></font>位访客";
    }
?>

A simple program for php visitor statistics. The above code counts the number of pv of the website. In addition to counting the number of pv (number of page visits) in the website, there are also statistics of uv (number of user visits). This requires adding cookies to distinguish each page. If a user already has a cookie, it means that they have visited, and no accumulation will be performed. Code such as:

<?php
    if(!empty($_COOKIE["access"]) && $_COOKIE["access"]==1){
        if(!file_exists("count.txt")){
            $one_file=fopen("count.txt","w+"); 
            echo"您是第<font color='red'><b>1</b></font>位访客"; 
            fwrite("count.txt","1");  
            fclose("$one_file");
            setcookie("access",1, time()+3600*24); //访问过标记
         }else{ 
            $num=file_get_contents("count.txt");
            $num++;
            file_put_contents("count.txt","$num");
            $newnum=file_get_contents("count.txt");
            echo"您是第<font color='red'><b>".$newnum."</b></font>位访客";
            setcookie("access",1, time()+3600*24);//访问过标记
        }
    }
?>

2. Obtain detailed statistics

In a public file of the website, statistics on the user's IP, browser type, system type, access time, current address, access source, and IP-to-locality information are obtained for each visit. Through this information, you can roughly know which place has the largest number of visitors, which article has the largest number of visitors, the number of visitors today, pv, malicious access ip and other information will come out.

1. Database table structure:

CREATE TABLE `visitors` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  `ip` char(30) DEFAULT NULL COMMENT 'ip地址',
  `froms` char(100) DEFAULT NULL COMMENT '归属地',
  `add_time` datetime NOT NULL COMMENT '添加时间',
  `system` char(60) DEFAULT NULL COMMENT '操作系统',
  `browser` char(200) DEFAULT NULL COMMENT '浏览器',
  `pageview` char(200) DEFAULT NULL COMMENT '受访页面',
  `source_link` varchar(1000) DEFAULT NULL COMMENT '来源链接',
  PRIMARY KEY (`id`),
  KEY `ip` (`ip`),
  KEY `add_time` (`add_time`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='访客表';

2. PHP statistics code

Place the code for obtaining information in a public php file and write it into the database.

//获取访客信息
//pdo连接数据库
$db_ms='mysql';
$db_host='127.0.0.1';
$db_user='root';
$db_pass='123456';
$db_name='test';
$dbh=$db_ms.':host='.$db_host.';'.'dbname='.$db_name;
try{
   $dbh = new PDO($dbh,$db_user,$db_pass);
   //echo '连接成功';
   $dbh -> query('set names utf8');
}catch(PDOException $e){
   die('error:'.$e->getMessage());
}
 
function visitor(){
    global $dbh;
    #当前url
    $url=$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    #获取ip和来源
    $address = GetIpFrom();
    $froms = $address[0];
    $ip = $address[1];
    #获取浏览器和系统类型
    $broswer = get_broswer();
    $os = get_os();
    
    #获取最后来源地址
    if(empty($_SERVER['HTTP_REFERER'])){
        $source_link = $url;
    }else{
        $source_link = $_SERVER['HTTP_REFERER'];
    }
    
    #限制ip访问次数
    $sqlco = "select count(id) as num FROM visitors where ip ="."'".$ip."'"." AND add_time>="."'".date('Y-m-d',time())."'";
 
    $cres = $dbh -> query($sqlco);
    $vnum = $cres -> fetch();
 
    if($vnum['num']>10000){
        exit('Sorry... You visited the number more than 10000 times today, and the access denied!');
    }
    #获取到的信息放入数据库
    $sql =" INSERT INTO visitors (ip,froms,add_time,system,browser,pageview,source_link) VALUES ('$ip','$froms',now(),'$os','$broswer','$url','$source_link')";
    $dbh -> exec($sql);
}

Browser information and ip information acquisition function

//获取浏览器信息
function get_broswer(){
    $sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
    if (stripos($sys, "Firefox/") > 0) {
        preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
        $exp[0] = "Firefox";
        $exp[1] = $b[1];  //获取火狐浏览器的版本号
    } elseif (stripos($sys, "Maxthon") > 0) {
        preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
        $exp[0] = "傲游";
        $exp[1] = $aoyou[1];
    } elseif (stripos($sys, "Baiduspider") > 0) {
        $exp[0] = "百度";
        $exp[1] = '蜘蛛';
    }elseif (stripos($sys, "YisouSpider") > 0) {
        $exp[0] = "一搜";
        $exp[1] = '蜘蛛';
    }elseif (stripos($sys, "Googlebot") > 0) {
        $exp[0] = "谷歌";
        $exp[1] = '蜘蛛';
    }elseif (stripos($sys, "Android 4.3") > 0) {
        $exp[0] = "安卓";
        $exp[1] = '4.3';
    }
    elseif (stripos($sys, "MSIE") > 0) {
        preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
        $exp[0] = "IE";
        $exp[1] = $ie[1];  //获取IE的版本号
    } elseif (stripos($sys, "OPR") > 0) {
        preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
        $exp[0] = "Opera";
        $exp[1] = $opera[1];
    } elseif(stripos($sys, "Edge") > 0) {
        //win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
        preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
        $exp[0] = "Edge";
        $exp[1] = $Edge[1];
    } elseif (stripos($sys, "Chrome") > 0) {
        preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
        $exp[0] = "Chrome";
        $exp[1] = $google[1];  //获取google chrome的版本号
    } elseif(stripos($sys,'rv:')>0 && stripos($sys,'Gecko')>0){
        preg_match("/rv:([\d\.]+)/", $sys, $IE);
        $exp[0] = "IE";
        $exp[1] = $IE[1];
    }else if(stripos($sys,'AhrefsBot')>0){
        $exp[0] = "AhrefsBot";
        $exp[1] = '蜘蛛';
    }else if(stripos($sys,'Safari')>0){
        preg_match("/([\d\.]+)/", $sys, $safari);
        $exp[0] = "Safari";
        $exp[1] = $safari[1];
    }else if(stripos($sys,'bingbot')>0){
        $exp[0] = "必应";
        $exp[1] = '蜘蛛';
    }else if(stripos($sys,'WinHttp')>0){
        $exp[0] = "windows";
        $exp[1] = 'WinHttp 请求接口工具';
    }else if(stripos($sys,'iPhone OS 10')>0){
        $exp[0] = "iPhone";
        $exp[1] = 'OS 10';
    }else if(stripos($sys,'Sogou')>0){
        $exp[0] = "搜狗";
        $exp[1] = '蜘蛛';
    }else if(stripos($sys,'HUAWEIM')>0){
        $exp[0] = "华为";
        $exp[1] = '手机端';
    }else if(stripos($sys,'Dalvik')>0){
        $exp[0] = "安卓";
        $exp[1] = 'Dalvik虚拟机';
    }else if(stripos($sys,'Mac OS X 10')>0){
        $exp[0] = "MAC";
        $exp[1] = 'OS X10';
    }else if(stripos($sys,'Opera/9.8')>0){
        $exp[0] = "Opera";
        $exp[1] = '9.8';
    }else if(stripos($sys,'JikeSpider')>0){
        $exp[0] = "即刻";
        $exp[1] = '蜘蛛';
    }else if(stripos($sys,'Baiduspider')>0){
        $exp[0] = "百度";
        $exp[1] = '蜘蛛';
    }
    else {
        $exp[0] = $sys;
        $exp[1] = "";
    }
    return $exp[0].' '.$exp[1];
}
 
//获取操作系统信息
function get_os(){
    $agent = empty($_SERVER['HTTP_USER_AGENT']) ? '未知' : $_SERVER['HTTP_USER_AGENT'];
    $os = false;
    if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent))
    {
        $os = 'Windows Vista';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent))
    {
        $os = 'Windows 7';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent))
    {
        $os = 'Windows 8';
    }else if(preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent))
    {
        $os = 'Windows 10';#添加win10判断
    }else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent))
    {
        $os = 'Windows XP';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent))
    {
        $os = 'Windows 2000';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent))
    {
        $os = 'Windows NT';
    }
    else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent))
    {
        $os = 'Windows 32';
    }
    else if (preg_match('/linux/i', $agent))
    {
        $os = 'Linux';
    }
    else if (preg_match('/unix/i', $agent))
    {
        $os = 'Unix';
    }
    else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent))
    {
        $os = 'SunOS';
    }
    else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent))
    {
        $os = 'IBM OS/2';
    }
    else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent))
    {
        $os = 'Macintosh';
    }
    else if (preg_match('/PowerPC/i', $agent))
    {
        $os = 'PowerPC';
    }
    else if (preg_match('/AIX/i', $agent))
    {
        $os = 'AIX';
    }
    else if (preg_match('/HPUX/i', $agent))
    {
        $os = 'HPUX';
    }
    else if (preg_match('/NetBSD/i', $agent))
    {
        $os = 'NetBSD';
    }
    else if (preg_match('/BSD/i', $agent))
    {
        $os = 'BSD';
    }
    else if (preg_match('/OSF1/i', $agent))
    {
        $os = 'OSF1';
    }
    else if (preg_match('/IRIX/i', $agent))
    {
        $os = 'IRIX';
    }
    else if (preg_match('/FreeBSD/i', $agent))
    {
        $os = 'FreeBSD';
    }
    else if (preg_match('/teleport/i', $agent))
    {
        $os = 'teleport';
    }
    else if (preg_match('/flashget/i', $agent))
    {
        $os = 'flashget';
    }
    else if (preg_match('/webzip/i', $agent))
    {
        $os = 'webzip';
    }
    else if (preg_match('/offline/i', $agent))
    {
        $os = 'offline';
    }else if (preg_match('/iPhone OS 8/i', $agent))
    {
        $os = 'iOS 8';
    }else if (preg_match('/YisouSpider/i', $agent))
    {
        $os = '一搜引擎';
    }else if (preg_match('/Yahoo! Slurp/i', $agent))
    {
        $os = '雅虎引擎';
    }else if (preg_match('/iPhone OS 6/i', $agent))
    {
        $os = 'iOS 6';
    }
    else if (preg_match('/Baiduspider/i', $agent))
    {
        $os = '百度引擎';
    }else if (preg_match('/iPhone OS 10/i', $agent))
    {
        $os = 'iOS 10';
    }else if (preg_match('/Mac OS X 10/i', $agent))
    {
        $os = 'Mac OS 10';
    }
    else if (preg_match('/Ahrefs/i', $agent))
    {
        $os = 'Ahrefs SEO 引擎';
    }
    else if (preg_match('/JikeSpider/i', $agent))
    {
        $os = '即刻引擎';
    }else if (preg_match('/Googlebot/i', $agent))
    {
        $os = '谷歌引擎';
    }else if(preg_match('/bingbot/i',$agent)){
        $os = '必应引擎';
    }else if(preg_match('/iPhone OS 7/i',$agent)){
        $os = 'iOS 7';
    }else if(preg_match('/Sogou web spider/i',$agent)){
        $os = '搜狗引擎';
    }else if(preg_match('/IP-Guide.com Crawler/i',$agent)){
        $os = 'IP-Guide Crawler 引擎';
    }else if(preg_match('/VenusCrawler/i',$agent)){
        $os = 'VenusCrawler 引擎';
    }
    else{
        $os = $agent;
    }
    return $os;
}

Get the client's real ip and ip attribution function

function GetIps(){  
      $realip = '';  
      $unknown = 'unknown';  
      if (isset($_SERVER)){  
          if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){  
              $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);  
              foreach($arr as $ip){  
                  $ip = trim($ip);  
                  if ($ip != 'unknown'){  
                      $realip = $ip;  
                      break;  
                  }  
              }  
          }else if(isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) && strcasecmp($_SERVER['HTTP_CLIENT_IP'], $unknown)){  
              $realip = $_SERVER['HTTP_CLIENT_IP'];  
          }else if(isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR']) && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)){  
              $realip = $_SERVER['REMOTE_ADDR'];  
          }else{  
              $realip = $unknown;  
          }  
      }else{  
          if(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), $unknown)){  
              $realip = getenv("HTTP_X_FORWARDED_FOR");  
          }else if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), $unknown)){  
              $realip = getenv("HTTP_CLIENT_IP");  
          }else if(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), $unknown)){  
              $realip = getenv("REMOTE_ADDR");  
          }else{  
              $realip = $unknown;  
          }  
      }  
      $realip = preg_match("/[\d\.]{7,15}/", $realip, $matches) ? $matches[0] : $unknown;  
      return $realip;  
  }  
    
  function GetIpFrom($ip = '')
    {
        if (empty($ip)) {
            $ip = GetIps();
        }

        $res = get_ip_city($ip);

        if ($res) {
            $address[0] = $res;
        } else {
            $address[0] = '';
        }
        $address[1] = $ip;

        return $address;
    }

    /**
     * $ip  string  必传
     * 获取ip归属地
     * demo 四川省成都市 电信
     */
    function get_ip_city($ip)
    {
        $ch = curl_init();
        $url = 'https://whois.pconline.com.cn/ipJson.jsp?ip=' . $ip;
        //用curl发送接收数据
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //请求为https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $location = curl_exec($ch);
        curl_close($ch);
        // 转码
        $location = mb_convert_encoding($location, 'utf-8', 'GB2312');
        // 截取{}中的字符串
        $location = substr($location, strlen('({') + strpos($location, '({'), (strlen($location) - strpos($location, '})')) * (-1));
        // 将截取的字符串$location中的‘,’替换成‘&’   将字符串中的‘:‘替换成‘=’
        $location = str_replace('"', "", str_replace(":", "=", str_replace(",", "&", $location)));
        // php内置函数,将处理成类似于url参数的格式的字符串  转换成数组
        parse_str($location, $ip_location);

        return $ip_location['addr'];
    }

The above functions can all be placed in a common file and call the function

visitor();

That's it. Other statistical functions are obtained through database query statistics, such as:

#查看pv
select count(*) as pv from visitors;
#查看uv、今日ip
select distinct(count(*)) as pv from visitors;
...

Guess you like

Origin blog.csdn.net/withoutfear/article/details/129027976