PHP Session Thoughts

This is terse, because I am Angry, because Firefox crashed. Angry angry.

PHP Sessions lock. only one page (or resource) will load at a time. Especially visible if you load up several iframes or frames or something and they are session’ed. Also will be very nuisancesome with AJAX and XMLHttpRequest – while page is loading or XMLHttpRequest is running, no other content will load.

Solution 1 is to say session_write_close() after you’ve finished writing to the session. This is okay, but there’s still some lock contention before you say session_write_close().

My solution was to write a custom Session handler that doesn’t lock. It only locks when the session is being written (don’t want to have two processes writing to the session file at the same time, that’s just a recipe for complete disaster). It’s a little dangerous – if you store important data in the session, it could get mangled. But if you mostly read from your sessions, and don’t write to it too often, and don’t care if your writes to the sessions get stomped, you can try my method.

I put it on PHP.net, but in case it should ever disappear, here’s what I did:

1) Steal the example from session_set_save_handler().

2) Modify the write() method to do an flock() on the file before it writes to it, and unlock the file after the write is finished.

3) Add a proper Garbage Collection routine.

And our testing has shown that now you can get multiple concurrent loads running. Be very very careful though – the lock-free nature of this means you could scribble all over yourself. Don’t say you haven’t been warned. We haven’t blown anything up yet, but QA is doing their damnedest to.

Leave a Reply

Your email address will not be published. Required fields are marked *