我想在我的stats.php网站上的“访问者在线: 001”更新访问者5秒。如果我重新加载页面,并打开另一个具有不同ip的设备,它就能工作。我真的很想在这方面提供一些帮助。这可能是一个小的代码,我可以包括,我可以改变,以更新计数器,否则任何事情都会帮助我。
<?php
/*************************************************************************
php easy :: online visitors counter scripts set - PHP Include Version
==========================================================================
Author: php easy code, www.phpeasycode.com
Web Site: http://www.phpeasycode.com
Contact: webmaster @ phpeasycode.com
*************************************************************************/
$servername = "localhost";
$username = "root";
$password = "12345678";
$dbname = "db";
// Connection to database
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
  if (mysqli_connect_errno())
    {
    echo 'NOT_OK';
    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
$dbfile = "visitors.db"; // path to data file
$expire = 300; // average time in seconds to consider someone online before removing from the list
if(!file_exists($dbfile)) {
die("Error: Data file " . $dbfile . " NOT FOUND!");
}
if(!is_writable($dbfile)) {
die("Error: Data file " . $dbfile . " is NOT writable! Please CHMOD it to 666!");
}
function CountVisitors() {
global $dbfile, $expire;
$cur_ip = getIP();
$cur_time = time();
$dbary_new = array();
$dbary = unserialize(file_get_contents($dbfile));
if(is_array($dbary)) {
while(list($user_ip, $user_time) = each($dbary)) {
if(($user_ip != $cur_ip) && (($user_time + $expire) > $cur_time)) {
$dbary_new[$user_ip] = $user_time;
}
}
}
$dbary_new[$cur_ip] = $cur_time; // add record for current user
$fp = fopen($dbfile, "w");
fputs($fp, serialize($dbary_new));
fclose($fp);
$out = sprintf("%03d", count($dbary_new)); // format the result to display 3 digits with leading 0's
return $out;
}
function getIP() {
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
elseif(isset($_SERVER['REMOTE_ADDR'])) $ip = $_SERVER['REMOTE_ADDR'];
else $ip = "0";
return $ip;
}
$visitors_online = CountVisitors();
?>
<p>Visitors online: <b><?=$visitors_online;?></b></p>
?>发布于 2019-04-04 11:19:00
就像评论说的..。
您可以使用Javascript/Ajax来实现这一点,原因是PHP是在页面加载时运行的,因此它只会显示页面加载时找到的值,因此让数据库调用在单独的文件中使用AJAX是可行的。
示例伪代码。
文件
getCustomerCount.php
$servername = "localhost";
$username = "root";
$password = "12345678";
$dbname = "db";
if(isset($_POST['getCustomerCount']))
{
    // Connection to database
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (mysqli_connect_errno())
    {
        echo json_encode(['success'=> false,'error_message'=>"NOT_OK"]);
        //echo 'NOT_OK';
        //echo "Failed to connect to MySQL: " . mysqli_connect_error();
        die();
    }
    $dbfile = "visitors.db"; // path to data file
    $expire = 300; // average time in seconds to consider someone online before removing from the list
    if(!file_exists($dbfile)) {
        echo json_encode(['success'=> false,'error_message'=>"Error: Data file " . $dbfile . " NOT FOUND!"]);
        die();
        //die("Error: Data file " . $dbfile . " NOT FOUND!");
    }
    if(!is_writable($dbfile)) {
        echo json_encode(['success'=> false,'error_message'=>"Error: Data file " . $dbfile . " is NOT writable! Please CHMOD it to 666!"]);
        die();
        //die("Error: Data file " . $dbfile . " is NOT writable! Please CHMOD it to 666!");
    }
    $count = CountVisitors($dbfile, $expire);
    if(is_numeric($count)){
        $out = sprintf("%03d", $count); // format the result to display 3 digits with leading 0's
        echo json_encode(['success'=>'true', 'customer_count'=>$out]);
    }
    else 
    {
        echo json_encode(['success'=> false, 'error_message'=>"count is not numeric"]);
    }
}
else{
    echo json_encode($_POST);
}
function CountVisitors() {
    global $dbfile, $expire;
    $cur_ip = getIP();
    $cur_time = time();
    $dbary_new = array();
    $dbary = unserialize(file_get_contents($dbfile));
    if(is_array($dbary)) {
        while(list($user_ip, $user_time) = each($dbary)) {
            if(($user_ip != $cur_ip) && (($user_time + $expire) > $cur_time)) {
                $dbary_new[$user_ip] = $user_time;
            }
        }
    }
    $dbary_new[$cur_ip] = $cur_time; // add record for current user
    $fp = fopen($dbfile, "w");
    fputs($fp, serialize($dbary_new));
    fclose($fp);
    return count($dbary_new);
}
function getIP() {
    if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    elseif(isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    else
    {
        $ip = "0";
    }
    return $ip;
}Javascript文件。
getCustomerCount.js
$(function(){
    //Set interval function to update after set time
    var timer = setInterval(function(){
        updateCustomerCount();
    }, 5000);
});
function updateCustomerCount()
{
    $.ajax({
        url:"getCustomerCount.php",
        type:"POST",
        data:{getCustomerCount:true},
        success:function(response){
            console.log(response);
            var data = $.parseJSON(response);
            if(data.success)
            {
                $("#customer_count span").text(data.customer_count);
            }
            else
            {
                console.log(data.error_message);
            }
        },
        error:function(response){
            console.log("Server Error");
        }
    });
}HTML文件。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
    <p id="customer_count">Customers Online: <span></span></p>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="getCustomerCount.js"></script>
</body>
</html>这对于你来说应该是一个如何做它的例子,但是我建议清理它并查看不同的部分,看看如何改进它们以供你使用。
https://stackoverflow.com/questions/55513144
复制相似问题