5

I am trying to serve two near simultaneous requests originating from the same browser session.

Consider the following minimal example:

<?php

session_start();

$sessionId = session_id();

session_write_close();

$file = sys_get_temp_dir() . '/lock_test';

if (!file_exists($file)) {

    touch($file);

    sleep(5);

    unlink($file);

    echo 'done! ' . $sessionId;

} else {

    echo 'locked! ' . $sessionId;

}

The second request should result in the "locked" output but it always waits for the first request to complete and then outputs "done".

Xdebug is not running. PHP version is 5.5.

Edit:

Voting to close this as a duplicate. The linked question suggests that to get around this issue, append a random variable. So I would suggest appending a requestTime variable and setting it to a timestamp with microseconds.

bcmcfc
  • 25,966
  • 29
  • 109
  • 181
  • How are you making said requests? – PeeHaa Jul 25 '14 at 09:00
  • Hit the script from a browser. Supposedly this method can be used to facilitate multiple ajax requests without them blocking each other for as long as they would without it. – bcmcfc Jul 25 '14 at 09:01
  • Have you tried removing the file IO (leaving just session start/close sleep and echo)? – Vatev Jul 25 '14 at 09:12
  • @Vatev the file IO is the crucial, required part. – bcmcfc Jul 25 '14 at 09:54
  • @bcmcfc the point was to make certain the locking is due to the session and not something else. – Vatev Jul 25 '14 at 09:58
  • @Vatev I've just tested it - 5 seconds for the first request, 10 for the second - so it's still locking just with `sleep()`, `echo`, `die()`. – bcmcfc Jul 25 '14 at 10:00
  • 3
    Found an answer here [PHP flock() non-blocking still block why?](http://stackoverflow.com/questions/13331809/php-flock-non-blocking-still-block-why). It explains the problem. Workaround would be to append a microtime variable to each request. – bcmcfc Jul 25 '14 at 10:33

1 Answers1

0

This behaviour is OK. If both requests share the same session and you are using files to store session data, PHP needs to flock() the session file to prevent it from getting corrupted by multiple, concurring requests which would attempt to write to the file. (Of course PHP will always flock() the session file, but having multiple concurring requests which share the same session, you can see it in effect)

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • But I am explicitly calling session_write_close, which is essentially me saying "ok, I've got what I want from this session file, this request does not need to write to it or read from it again". – bcmcfc Jul 25 '14 at 09:36
  • Ok, understood. Your expectation is valid. Would need to investigate this. – hek2mgl Jul 25 '14 at 09:58