如何每秒更新一次php中的值

时间:2019-04-04 10:02:06

标签: php html ajax web reload

我希望stats.php网站上的“在线访客:001”将访客更新5秒。如果我重新加载页面并在打开页面时让另一个设备具有不同的ip,它会起作用。我真的很感谢您的帮助。这可能是一个很小的代码,我可以包括其中可以更改以更新计数器,否则任何可以帮助我的事情。

Here`s a image showing the counter

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

1 个答案:

答案 0 :(得分:0)

就像评论说的那样。

您可以使用Javascript / Ajax进行此操作,其原因是PHP在页面加载时运行,因此它将仅显示页面加载时找到的值,因此可以在单独的文件中进行数据库调用与AJAX通话是必经之路。

示例伪代码。

PHP文件
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>

以它为例,它应该为您工作,但是我建议您清理一下并研究各个部分,以了解如何在使用时对其进行改进。