tags:

views:

128

answers:

3

So here's my test setup:

session_start();
if(!isset($_SESSION['bahhhh']))
    $_SESSION['bahhhh'] = 0;
$_SESSION['bahhhh']++;
sleep(5);
die('a'.$_SESSION['bahhhh']);

What I expect to happen is that each time I hit the page, it returns a different number.

But if I use multiple tabs, and refresh them each within 5 seconds of the first, they all return the same number. (This isn't client side caching, as the 5 second delay is still evident.)

Why is it doing this, and how do I fix this?

It seems to have the same strange caching issue with file and database data as well, and is preventing me from building a working mutex to prevent running the same code more than once at a time.

Here's another, simpler example:

echo microtime();
sleep(10);

Run this 3 times, each 2 seconds apart, and all three return the same microsecond. WTF?

+6  A: 

Session data, be default, is not saved until the request terminates. So your increment is not saved while sleeping. If you want to save the session prematurely checkout session_write_close()

Mike B
As I said, I also used file and database backends to this approach. Here's another test script that fails to behave as expected:echo microtime();sleep(10);If you open that in multiple tabs, then refresh each within 10 seconds of each other, ever tab will claim it was called on the exact same microsecond (a clear impossibility).
VexedPanda
I don't understand what storage medium as to do with your issue. I tested your script in 5 tabs, refreshing each within 10 seconds of each other and got different output each time. Tested with latest 5.2.x on ubuntu 9.10.
Mike B
A: 

I would have the script itself append something to a log file to verify the script is actually getting executed as many times as you think. Maybe you have some software somewhere that is intercepting the request and returning a cached response.

If it weren't for your comment that this also happens with microtime(), I would have given an explanation of how php manages concurency with sessions, and when it might not.

chris
The difficulty in writing to a file is that since things like microtime() return the same result for all instances, I wouldn't be able to differentiate between all three writing to the file (since it'd end up being the same filename), or only one.That said, the error we're encountering in production is that a maintanence script is running more than once, and encountering race conditions with itself, so I'm sure all three copies are actually executed. This is why we are attempting to build a mutex.
VexedPanda
A: 

Apparently this is some bug in my browser itself. Opera behaves this way while Internet Explorer does not. I did initial testing in IE with the same results but with more complex code. Apparently that complex code had an error that triggered the misbehavior in IE, and this simplified code does not. Sorry to bother everyone.

VexedPanda