I am working on a webpage that shows the amount of online players on a game server in real time.
The problem is that I can get the amount of players online in the game server displayed in the website, but after loading the page it never updates and it always stays as the initial amount of players, although lots of people join and leave the server every second.
This is the PHP code that I am using to show the numbers:
<?php
echo "<a id='a1' href='#' class='online'>Loading...</a>";
?>
What I am doing is to update 'a1' every second with the new amount of online players using javascript, which updates it with a php function called 'getplayers()':
<script language="JavaScript">
setInterval(function(){
document.getElementById("a1").innerHTML = '';
}, 1000);
</script>
The function 'getplayers()' is like:
<?php
include "Status.php";
function getplayers() {
$serverb = new Status("127.0.0.1", '17171');
return $serverb->online_players;
}
?>
Lastly, Status.php is a php script that gets the amount of players online and more things about the server, which I am sure that works:
<html>
<?php
class Status {
public $server;
public $online, $motd, $online_players, $max_players;
public $error = "OK";
function __construct($url, $port = '25565') {
$this->server = array(
"url" => $url,
"port" => $port
);
if ( $sock = @stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) {
$this->online = true;
fwrite($sock, "\xfe");
$h = fread($sock, 2048);
$h = str_replace("\x00", '', $h);
$h = substr($h, 2);
$data = explode("\xa7", $h);
unset($h);
fclose($sock);
if (sizeof($data) == 3) {
$this->motd = $data[0];
$this->online_players = (int) $data[1];
$this->max_players = (int) $data[2];
}
else {
$this->error = "Cannot retrieve server info.";
}
}
else {
$this->online = false;
$this->error = "Cannot connect to server.";
}
}
}
?>
</html>
So my question is if someone knows why it always updates with the first number of players instead of putting the new number of players?