I am trying to implement simple longpolling in php, my server code goes like this:
if (!isset($_SESSION["lastResult"])) {
$_SESSION["lastResult"] = "";
}
while(true){
$sql = "SELECT * from table";
$result = mysqli_query($conn, $sql);
$array = [];
while ($row = $result->fetch_array()) {
do something and insert each element into $array;
}
$jsonRes = json_encode($array);
//if old array is different from the new one, that means information has been updated,
//so I need to echo new data to user.
if (strcmp($jsonRes, $_SESSION["lastResult"]) == 0) {
echo $jsonRes;
$_SESSION["lastResult"] = $jsonRes;
exit();
}
//If information hasn't changed, just sleep for 5 seconds and repeat next time.
sleep(5);
}
and client code:
const waitForData = () => {
//this is just a js fetch function
getDataHTTP().then(res => {
this.setState({ itemsData: res });
waitForData ();
});
};
waitForData();
But what happens is in my network tab, I see my getData php script "pending" as it should, but its pending forever, and the other thing is that I can't really edit any other data on the webpage, because for some reason, which I assume is the sleep()
function, All my php scripts stop working, and are forever "Pending".
Thanks in advance.
Edit:
Just for the record, $_SESSION variable works, all data is where it should be. Same is with SQL query, it returns everything correctly.
Edit2:
I am not getting any errors except max execution time.