Wherein I occasionally rant on various topics including, but not limited to, PHP, Music, and whatever other Topics I find interesting at the moment, including my brain tumor surgery of August 2010.

Friday, October 30, 2009

PHP, Frames, and Sessions

Any time you try to use frames and PHP sessions, you are likely to run into trouble.

It's basically a race condition just waiting to blow up in your face:

1. Frame A sends HTTP request, with no session Cookie
2. PHP/server processes request, with no session Cookie, so creates NEW session
3. Frame B sends HTTP request, with no session Cookie
4. Frame A receives response, with session Cookie from Step 2.
5. PHP/server processes request, with no session Cookie, so creates NEW session
6. Frame B receives response, with different session Cookie from Step 5.

See Step 4 the browser *gets* the cookie it needed in step 3 for there to be just ONE session?

Your best bet is to initialize the session in a frame-less landing page, and then move forward with frames. Once the user has the session Cookie, all the frames can "share" it.

You'll have to redirect a session-less user to that frame-less page and back again, however, which uses up a lot of HTTP connections, and so is resource-intensive.

Note that Frame A and Frame B steps could actually interleave in ANY order, really. Each request is completely independent of the other.

And *some* orderings are actually going to "work", so you may not find this bug until your server gets busy enough that HTTP requests/responses start to lag a little bit.

1 comment:

Sonny Huynh said...

I didn't remember "Race Condition" at first but THANKS to the link it (electronics circuitry) comes right back as I was trained as a -e technician some 28 years ago. Thanks Richard