views:

443

answers:

3

Suppose a user is editing a record from a database, in the schema you have a field named 'lock' so users can not edit concurrently the same record, once the user ends editing you set lock = false to allow other users to edit the record.

My question is, can i run some code when php session ends, so if a user walks away from computer, close the browser or whatever, i can set the lock to false?. Because if not, and correct me if I'm wrong, the record would remain locked?

I've read the session_set_save_handler section from php manual, but i'm not sure that the 'close' callback it's what i need...

Or do I need to add a timestamp in the db schema and run a cronjob to 'unlock' the records every x time?

Thanks!

+1  A: 

I think you're better of with the lock timestamp you described. The problem with the session closed callbacks is that you can never be certain that they get called. For instance, what happens if someone shuts down your webserver, or worse, kills the process. You want DB consistency in those situations as well.

Sander Rijken
A: 

Perhaps this is something you would do in a register_shutdown_function().

Zoredache
Well, correct me if I'm wrong. From the manual "the registered shutdown functions are called after the request has been completed" So if I have a edit.php the function would execute after the page has loaded and the lockgets released and other users could made modifications concurrently
Cesar
A: 

I would not want to implement locking using your approach as described above, simply because of the reasons you mentioned in the second paragraph.

What I would do is to have a timestamp column in the table. Whenever an attempt is made to write to that table, it should be read first then its timestamp noted (say, in a session variable somewhere). Before writing the updated information back into the row I will take a look at the timestamp and ensure that its timestamp is exactly the same one that I saw (and noted in the session var). If it's not, someone updated the row while I wasn't looking (in this case, while you presented a form to the user and the user has not submitted the form back to the server yet).

This approach is what many O/RMs use to ensure that one session is not overwriting changes made in another session inadvertently. The upside to this approach is that you do not run the chance of a "lock" getting left by a user who's abandoned the session, and you don't need to have a cron job to unlock stale locks. The downside to this approach is that you would only know about the collision the moment you try to update the record in the DB. This means the user would have already submitted a form containing the data changes, and you would have to inform the user that he/she has to try again (after, say, presenting the updated/latest information from that record).

cruizer