Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP session handling when the same client requests the same script multiple times at once

Tags:

php

session

mutex

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?

like image 756
VexedPanda Avatar asked May 14 '26 01:05

VexedPanda


1 Answers

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()

like image 144
Mike B Avatar answered May 15 '26 15:05

Mike B