user3195616
user3195616

Reputation: 305

PHP $_SESSION not shared between requests

I am playing with long polling and trying to stop the script started by an AJAX call if a new request happens. This is the PHP code that is started by an AJAX request:

$checker = $_SESSION['checker'] = time();

while (true) {
    if ($checker != $_SESSION['checker']) {
          $out = 'new one started';
          break;
     }

    if (some other condition) {
           $out = 'smth done or happend';
           break;
    }

    sleep(3); 
}

echo $out;

I have been doing some logging and it looks like $_SESSION['checker'] is not updated, so if I run same script (which should change the $_SESSION['checker'] variable), the while loop in the previously started script will still see the old $_SESSION['checker']. Why is it not updated?

Upvotes: 2

Views: 628

Answers (2)

Pieter van den Ham
Pieter van den Ham

Reputation: 4514

PHP sessions do not support concurrent read/write operations by default. That is, when you update the $_SESSION array from one request, it does not propagate to an already running PHP request.

A solution is to create a file, and monitor the filemtime (file modification time) of that file. Whenever we see that the file is updated, we know that another process touched it.

Implementation example:

$filename = ".test_file";

// Update the file modification time to the current time
touch($filename);
$modificationTime = filemtime($filename);

while ($modificationTime === filemtime($filename) {
    // Do stuff, file modification time is not yet updated.
}

// The file modification time has been updated!

Note that you should test for the change frequently, depending on how quickly the first process should terminate, which means that the code inside the while loop should not take too long.

Upvotes: 3

Pim Broens
Pim Broens

Reputation: 702

You might want to tackle this from the ajax side instead of the PHP side. You can stop current http requests through abort, something like:

var xhr = $.ajax({
    type: "POST",
    url: "file.php",
    data: "parameter=input&type=test",
    success: function(msg){
       alert( "Data Saved: " + msg );
    }
});

//kill the request
xhr.abort()

Upvotes: 1

Related Questions