這篇文章主要介紹了PHP簡單實現記錄網站訪問量功能,涉及php針對檔案加鎖讀寫及日期時間轉換等相關操作技巧,需要的朋友可以參考下
本文執行個體講述了PHP簡單實現記錄網站訪問量功能。分享給大家供大家參考,具體如下:
tongji/index.php檔案:
$file = dirname(__FILE__).'/tongji.db';//$data = unserialize(file_get_contents($file));$fp=fopen($file,'r+');$content='';if (flock($fp,LOCK_EX)){while (($buffer=fgets($fp,1024))!=false){$content=$content.$buffer;}$data=unserialize($content);//設定記錄索引值$total = 'total';$month = date('Ym');$today = date('Ymd');$yesterday = date('Ymd',strtotime("-1 day"));$tongji = array();// 總訪問增加$tongji[$total] = $data[$total] + 1;// 本月訪問量增加$tongji[$month] = $data[$month] + 1;// 今日訪問增加$tongji[$today] = $data[$today] + 1;//保持昨天訪問$tongji[$yesterday] = $data[$yesterday];//儲存統計資料ftruncate($fp,0); // 將檔案截斷到給定的長度rewind($fp); // 倒迴文件指標的位置fwrite($fp, serialize($tongji));flock($fp,LOCK_UN);fclose($fp);//輸出資料$total = $tongji[$total];$month = $tongji[$month];$today = $tongji[$today];$yesterday = $tongji[$yesterday]?$tongji[$yesterday]:0;echo "document.write('訪總問 {$total}, 本月 {$month}, 昨日 {$yesterday}, 今日 {$today}');";}
使用方法(通過js引入tongji/index.php檔案):
<script language="JavaScript" src="./tongji/"></script>
運行結果: