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

全屏阅读
  • 基本信息

一、文件方式简单统计

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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,说明访问过,不再进行累加。代码如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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.数据库表结构

1
2
3
4
5
6
7
8
9
10
11
12
13
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文件中放置获取信息代码,并写入到数据库中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//获取访客信息
//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信息获取函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//获取浏览器信息
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归属地函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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($locationstrlen('({') + 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'];
    }

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

1
visitor();

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

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

顶一下
(0)
100%
订阅 回复
踩一下
(0)
100%
» 郑重声明:本文由mpxq168发布,所有内容仅代表个人观点。版权归恒富网mpxq168共有,欢迎转载, 但未经作者同意必须保留此段声明,并给出文章连接,否则保留追究法律责任的权利! 如果本文侵犯了您的权益,请留言。

目前有 0 条留言 其中:访客:0 条, 博主:0 条

给我留言

您必须 [ 登录 ] 才能发表留言!