<?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']; //查看當天時間