php实现一个简单的访客统计功能

一、文件方式简单统计

用php实现一个简单的访客统计功能,统计网站的总访问量是多少,简单实用。php通过每次打开文本文件,获取文本中的数字,进行加1再写入到文本中。所以只要每次有访问就会进行累加pv数量来实现的简单访客次数的统计。

<?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>位访客";
    }
?>

php访客统计简单程序,上面的代码统计了网站的pv数,网站中除了要统计pv(页面访问次数)数,还有uv(用户访问次数)的统计,这是需要加上cookie来区别开每个用户,如果已经存在cookie,说明访问过,不再进行累加。代码如:

<?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);//访问过标记
        }
    }
?>

二、获取详细信息统计

在网站的一个公共文件中,进行每次访问时获取用户的ip、浏览器类型、系统类型、访问时间、访问当前地址、访问来源、ip对属地信息的统计。通过这些信息就能大致知道哪个地方访问人数最大、哪篇文章访问人数最大、今日访问人数、pv、恶意访问ip等信息就都出来了。

1.数据库表结构:

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统计代码

在一个公共php文件中放置获取信息代码,并写入到数据库中。

//获取访客信息
//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);
}

浏览器信息和ip信息获取函数

//获取浏览器信息
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;
}

获取客户端真实ip和ip归属地函数

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 = @file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
 
      if($res){
          $json = json_decode($res,true);
      }else{
          $json = '';
      }
 
      //var_dump($json);
 
      $address[0] = $json['data']['country'].$json['data']['region'].$json['data']['city'].$json['data']['isp'];
$address[1] = $ip;
 
return $address;
  }

上面的函数可以都放在一个公共的文件中,并调用函数

visitor();

即可。其他统计的功能都通过数据库查询统计出来,如:

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

转载: https://zixuephp.net/article-113.html

https://zixuephp.net/

原文链接:,转发请注明来源落伍老站长!

发表评论