<p>以下是实时更新的代码:</p>
<?php
//设置定时器,每3秒钟刷新一次
header("refresh:3");

function sxcs(){
    $list = file_get_contents('sxcs.dat');
    $myfile = fopen("sxcs.dat", "w");
    $sxcs = ($list+1);
    fwrite($myfile,"$sxcs");
    fclose($myfile);
    return $sxcs;
}

function slzxrs(){
    $online_log = "slzxrs.dat";
    $timeout = 30;
    $entries = file($online_log);
    $temp = array();
    for ($i=0;$i<count($entries);$i++){
        $entry = explode(",",trim($entries[$i]));
        if(($entry[0] != getenv('REMOTE_ADDR')) && ($entry[1] > time())) {
            array_push($temp,$entry[0].",".$entry[1]."\n");
        }
    }
    array_push($temp,getenv('REMOTE_ADDR').",".(time() + ($timeout))."\n");
    $slzxrs = count($temp);
    $entries = implode("",$temp);
    $fp = fopen($online_log,"w");
    flock($fp,LOCK_EX);
    fputs($fp,$entries);
    flock($fp,LOCK_UN);
    fclose($fp);
    return $slzxrs;
}

//获取当前在线人数和累计观看人数
$onlineNum = slzxrs();
$totalNum = sxcs();

//将数据写入json文件
$data = array('onlineNum' => $onlineNum, 'totalNum' => $totalNum);
$jsonStr = json_encode($data);
$file = fopen('data.json', 'w');
fwrite($file, $jsonStr);
fclose($file);

?>
<!--在页面上通过ajax实时获取数据-->
<h6><center><p>当前在线:<span id="onlineNum"></span> 人_ 累计观看人数:<span id="totalNum"></span> 人</p></center></h6>
<script>
    //使用ajax实时获取json文件中的数据
    setInterval(function(){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var data = JSON.parse(this.responseText);
                document.getElementById("onlineNum").innerHTML = data.onlineNum;
                document.getElementById("totalNum").innerHTML = data.totalNum;
            }
        };
        xmlhttp.open("GET", "data.json", true);
        xmlhttp.send();
    }, 3000);
</script>
用PHP写一个功能把下面代码的当前在线人数和累次观看人数写成实时更新数据的只在本页面实现 phpfunction sxcs$list = file_get_contentssxcsdat;$myfile = fopensxcsdat w;$sxcs = $list+1;fwrite$myfile$sxcs;fclose$myfile;return $sxcs;function slzxrs首

原文地址: https://www.cveoy.top/t/topic/b8cP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录