I have two files named playermonitor.php
and keepplayeralive.php
playermonitor.php
is supposed to run an infinite loop with an interval of 1 second
and keep checking the value of column status
in the table players
of a database, if it is equal to 0
, then increase $count
else set the value of the column to 0
. If $count
becomes equal to 3
, delete the table from the database. It is as follows
<?php
session_start();
ignore_user_abort(true);
set_time_limit(0);
/*if (true) is used for testing only*/
if (true) {
$_SESSION['playermonitorisrunning'] = 1;
$link = mysqli_connect('host', 'username', 'password', 'database name');
$playerid = $_SESSION['playerid'];
$count = 0;
while (true) {
$result = mysqli_query($link, "SELECT `status`, `gameid` FROM `players` WHERE `playerid` = ".$playerid.";");
$player = mysqli_fetch_array($result);
$playerstatus = $player['status'];
$gameid = $player['gameid'];
if ($playerstatus == 0) {
$count += 1;
if ($count == 3) {
$result = mysqli_query($link, "SELECT * FROM `games` WHERE `gameid` = ".$gameid.";");
if (mysqli_num_rows($result)) {
$game = mysqli_fetch_array($result);
$gameid = $game['gameid'];
$playercount = $game['playercount'] - 1;
for ($suff = 1; $suff <= $game['playerlimit']; $suff++) {
$playerslotname = 'player'.$suff;
if ($game[$playerslotname] == $playerid) {
break;
}
}
$result = mysqli_query($link, "UPDATE `games` SET `playercount` = ".$playercount.", `".$playerslotname."` = NULL WHERE `gameid` = ".$gameid.";");
}
$result = mysqli_query($link, "DELETE FROM `players` WHERE `playerid` = ".$playerid.";");
break;
}
}
else {
$result = mysqli_query($link, "UPDATE `players` SET `status` = 0 WHERE `playerid` = ".$playerid.";");
$count = 0;
}
sleep(1);
}
}
die();
?>
And the keepplayeralive.php
is supposed to run an infinite loop with an interval of 0.5 seconds
, and keep setting the value of the column status
of the table players
in the database to 1
. And it should break the loop when the user closes the connection. It is as follows
<?php
session_start();
ignore_user_abort(true);
set_time_limit(0);
$link = mysqli_connect('host', 'username', 'password', 'databse name');
$playerid = $_SESSION['playerid'];
while (true) {
$result = mysqli_query($link, "UPDATE `players` SET `status` = 1 WHERE `playerid` = ".$playerid.";");
if (connection_aborted()) {
break;
}
sleep(0.5);
}
die();
?>
I call these scripts asynchronously through JavaScript using XMLHttpRequest like this
var keepplayeronline = new XMLHttpRequest();
keepplayeronline.open("GET", "keepplayeronline.php", true);
keepplayeronline.send();
var playermonitor = new XMLHttpRequest();
playermonitor.open("GET", "playermonitor.php", true);
playermonitor.send();
If this all worked fine, the row in the database with value of column playerid
equal to $playerid
should get deleted after the user closes the connection.
However, the row doesn't get deleted after I close my connection to the server. What am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire