Clean up on closing the browser

Hi All,

I am building a seat booking website. When a user chooses their seats the seat is written to the database with a state of locked, and changed to the correct state eg reserved, taken when the user checks out, this is so other users of the website or at the point of sales can’t checkout the same seat. A none authenticated user can select seats and then registers at the end. The object containing all the seats is held in a session variable.

What i need is a way to remove the rows in the database if the user closes the browser. So a couple of questions, is an objects __destruct method called when a user closes the browser? is there a function to run when the session is ended or browser closed? I see the session_set_save_handler() but it’s called after object destruction so i wouldn’t be able to remove the rows that are stored in the object. Or any other ideas to implement this would be very much appreciated, i’m a bit stuck!

Kind Regards

Sadly there is no (fully reliable) way to detect when the user closes their browser.

As an alternative what I would do in situation like this is to reserve the seat for a set amount of time after the user clicked on it. So when the user clicks a seat you set the state to “reserved” and also set a “reserved_time” (new field). Then you check if a seat is reserved by checking if “reserved” is set to 1 AND the time recorded in “reserved_time” is within the last 15 minutes.

Alternatively you could let people register first and only when they have done so allow them to pick a seat, but this is (probably, I’m not an expert so I’m not 100% sure about this) less favorable in terms of conversion rate.

To directly answer your question, no PHP function/method will be called when you close the browser. You could write a piece of javascript that does an AJAX call, but this is extremely fragile and TBH I wouldn’t even try creating this for this very reason.

OK Thanks Scallio, i built the thing assuming php had this functionality either by object descruct or session destruct, which was a bit stupid. the locked seat can only be locked for a max of 15mins and i can clear it if the user browses to a different page so i guess its just a case of running a cronjob and clearing the database that way.

Thanks for your time.