Race Conditions, AJAX and Sessions

    Harry Fuecks
    Share

    Via Jeff’s bookmarks, Race Conditions with Ajax and PHP Sessions by Andy “thwarted” Bakun is an outstanding anaylsis of a problem that’s come up before on this blog here.

    In fact the title is almost misleading – the first half looks at “parallel processing” in Javascript with some valuable insight – i.e. you want to read this even if you’re not using PHP.

    The second half explores building a custom PHP session handler (PHP’s default session handler does not suffer from race conditions but can become problematic the moment you start handling serious traffic), leading up to a very cunning strategy that allows you to lock a single session variable (rather than the entire session) via overloading the $_SESSION variable using SPL – effectively an alternative to using session_set_save_handler() – let’s hope this becomes recognised as a feature that needs supporting.

    And it’s refresshing it is to see something like this in PHP-related content…

    the built-in [PHP] session handler uses the flock(2) system call […] This can be verified by using strace to list all the system calls being made by a process. Here’s the important bit:

    open("/var/lib/php/session/sess_XXXXXXXXXXXXXXXXXXXXXXXXXX", O_RDWR|O_CREAT, 0600) = 18
    flock(18, LOCK_EX)                      = 0
    fcntl64(18, F_SETFD, FD_CLOEXEC)        = 0
    fstat64(18, {st_mode=S_IFREG|0600, st_size=11, ...}) = 0
    pread64(18, "count|i:17;", 11, 0)       = 11
    . . . .
    pwrite64(18, "count|i:18;", 11, 0)      = 11
    close(18)                               = 0
    

    Side note – find myself agreeing with much of Andy’s Problems with PHP – much closer to the mark than the sort of gripes you typically find on the PHP sucks web ring.