John Pangilinan
John Pangilinan

Reputation: 1031

AJAX Long Polling with PHP Sessions

I have the following:

SCRIPT:

function poll(){
    $.ajax({
        ...
        url: poll.php,
        success: function(res){
            $('#count').html(res);
            poll();
        }
    });
}
poll();

poll.php:

session_start();
$count = $_SESSION['count'];
session_write_close();
while(true){
    $newcount = $_SESSION['count'];
    if($newcount != $count){
        $count = $newcount;
        break;
    }
    sleep(1);
}
echo $count;

In my php, when ever the $_SESSION['count'] is changed, it breaks out of the while loop then updates the DOM element '#count then polls again for changes. But my problem is, when i tried to change the $_SESSION['count'] from another instance, the instance running the poll keeps on waiting for the request the finish. It means that in my poll.php it doesn't break out of the while loop even if i changed the $_SESSION['count'] from another instance.

What is the problem here?

Upvotes: 0

Views: 1094

Answers (1)

jbafford
jbafford

Reputation: 5668

After you session_write_close(), the session is closed. That means that further changes are not reflected in $_SESSION.

You will need to re-open the session in order to read from it:

session_start();
$count = $_SESSION['count'];
session_write_close();
while(true){
    session_start();
    $newcount = $_SESSION['count'];
    session_write_close();

    if($newcount != $count){
        $count = $newcount;
        break;
    }
    sleep(1);
}
echo $count;

Note, however, that running an infinite loop like this on your webserver is generally not a good idea. You can easily leave yourself open to a denial-of-service attack: each php session running in that infinite loop is consuming memory and an open connection to the web server, so you can very quickly wind up with your web server being unable to respond to requests because all of its workers are tied up spinning in an infinite loop.

If you do need to do this in PHP, I would highly recommend the workers automatically exit after a certain period of time. Better still would be to use other technologies that are specifically intended for long-polling (such as, for example, a node.js WebSockets server).

Upvotes: 2

Related Questions