智能文章系统实战-数据统计(13)

admin 发布于:2018-7-1 16:53  有 2045 人浏览,获得评论 0 条  

1. 数据文件

 

#cat /var/log/nginx/news.demo.com.access.log-20180701
192.168.100.1 - - [01/Jul/2018:15:59:48 +0800] "GET http://news.demo.com/h5.php HTTP/1.1" 200 3124 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" "-"
192.168.100.1 - - [01/Jul/2018:16:00:03 +0800] "GET http://news.demo.com/h5.php?action=show&id=128 HTTP/1.1" 200 1443 "http://news.demo.com/h5.php" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" "-"
192.168.100.1 - - [01/Jul/2018:16:00:22 +0800] "GET http://news.demo.com/h5.php HTTP/1.1" 200 3124 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" "-"
192.168.100.1 - - [01/Jul/2018:16:00:33 +0800] "GET http://news.demo.com/h5.php?action=show&id=89 HTTP/1.1" 200 6235 "http://news.demo.com/h5.php" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" "-"


2. 数据表结构

 

CREATE TABLE IF NOT EXISTS `stat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stat_date` varchar(30) NOT NULL DEFAULT '' COMMENT '统计日期',
  `pv` int(11) NOT NULL DEFAULT '0' COMMENT 'PV量',
  `ip` int(11) NOT NULL DEFAULT '0' COMMENT 'IP量',
  PRIMARY KEY (`id`),
  UNIQUE KEY `stat_date` (`stat_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文章阅读统计' AUTO_INCREMENT=1 ;

 

 

3. 统计代码

 

<?php
header("Content-Type:text/html;charset=utf-8");
error_reporting(E_ALL & ~E_NOTICE);
date_default_timezone_set('PRC'); 


$pv=0;
$ip=0;
$ipList=array();

$yestoday=date("Y-m-d",time()-86400); //实际读取昨天的日志
$yestoday='2018-07-01'; //读取2018-07-01的日志,用来测试
$fileName=date('Ymd',strtotime($yestoday));
//读取日志文件
$logPath="/var/log/nginx/news.demo.com.access.log-{$fileName}";
if(file_exists($logPath))
{
	$fileContents=file_get_contents($logPath);
	$fileArray=explode("\n",$fileContents);
	foreach($fileArray as $str)
	{
		//过滤只有阅读文章内容的数据
		if(strpos($str,'action=show'))
		{
			
			$tempArray=explode(" ",$str);
			
			//统计PV
			$pv=$pv+1;
			
			//统计IP
			$userip=$tempArray[0];
			if(!in_array($userip,$ipList))
			{
				$ipList[]=$userip;
				$ip=$ip+1;
			}
		}
	}
}



//插入MYSQL数据库
$mysqli = new mysqli('localhost', 'root', '', 'article');
$sql="INSERT INTO stat SET stat_date='{$yestoday}',pv={$pv},ip={$ip}";
$mysqli->query($sql);
$mysqli->close();


?>
 


 

4. 统计结果

 

//统计结果
MariaDB [article]> select * from stat;
+----+------------+----+----+
| id | stat_date  | pv | ip |
+----+------------+----+----+
|  1 | 2018-07-01 |  2 |  1 |
+----+------------+----+----+
1 row in set (0.00 sec)