Search code examples
phpajaxsleep

PHP/AJAX: Is it sleep() that blocks all requests to the same script?


I have a PHP script which, when called, does some stuff, then sleeps for 3 seconds, then echoes its result.

And then I have this page which calls the script above (with an Ajax request) every 1/10 of second. When I get the response, I write a number inside a div element.

The problem is, the onreadystatechange handler is fired every 3 seconds, and writes 30 numbers all together. Are there any other alternatives to sleep() that behave like I need?

Here is the code snippet of the page that gets requested:

ignore_user_abort(true);
$time=microtime(true)*10000;
changemystatus(1, $time); //this writes to a database
sleep(3);
if ($time>=getmytime()){ //getmytime() reads the data previously written by changemystatus()
    setstatus(0); // still writing to that DB
    echo("1");
}else echo ("0");

Basically I want the "status" field in the DB to be changed to 0 if the user is not sending requests anymore (because he's gone, or his connection went down, or he has disabled JS or whatever) so that other players may know he's now "offline".


Solution

  • New answer: if you want to detect if users are still active record the timestamp of their last communication with the server.

    Then define some cutoff point, say: 5 minutes.

    if ($last_active < (time() - 5 * 60)) {
        // user is inactive
    }