PHP实现记录网站访问量统计功能示例

本文深入剖析了PHP实现的网站统计代码,详细介绍了如何通过读取和更新本地数据库文件来统计网站的总访问量、月访问量、日访问量及昨日访问量。文章展示了如何使用锁机制确保数据的一致性和原子性,以及如何通过JavaScript调用该统计脚本。

tongji/index.php

<?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>

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值