php查看当天访问量代码,以及每天访问量历史记录(本方法是存文件里,不是存数据库)

<?php
$fp = fopen("counter.txt", "r+");
$str_news=file_get_contents("counter.txt");//读取文件值,格式为:(当天访问次数,当天时间)
if(flock($fp, LOCK_EX)){//文件锁,防止冲突
$count = explode(',',$str_news);
$counter = $count['0'];//当天访问次数
$time1 = $count['1'];//当天时间
$untime=strtotime($time1);//转换为时间戳
$now = date('Y-m-d',time());//获取当前时间
$unnow = strtotime($now);
if($untime==$unnow){ //如果相等为当天的访问,否则为下一天的访问量
$counter++;
$str=$counter.','.$time1;
fwrite($fp,$str); //把当天的访问次数更新存入文件
}else{
$str=$counter.','.$time1;
file_put_contents('main.txt',var_export($str,TRUE),FILE_APPEND);//把前一天的数据存入main.txt文件,作为历史记录
$str1='1,'.$now; //新的一天,新的访问量开始
fwrite($fp,$str1);
}

flock($fp, LOCK_UN); // 释放文件锁
}

fclose($fp);

$aa=file_get_contents("counter.txt");
$arr=explode(',',$aa);
echo $arr['0']; //查看当前天数访问量
echo $arr['1']; //查看当天时间

原文地址:https://www.cnblogs.com/hualingyun/p/9118116.html