Lock content to edit the same file while being edited in browser.

In one of my projects users are allowed to edit the same file. It is group work and max number of users in group is 4. It is rare that they will be editing at the same time but there is possibility of it. How I can lock the content while it is being edited?

Use a lockfile.

Before you open the file you check if a lockfile exists.

[php]
$filename = $_REQUEST[‘filename’];
$lockname = $filename. ‘.lck’;
$write = true;

if ( file_exists( $lockname ) )
{ $fh = fopen( $lockname, ‘r’ );
// Check whether the username in the file is the same as the user logged in.
// if that’s not true, set $write to false and show
// Some warning about the file being edited
fclose( $fh );
}

if ( $write )
{ $fh = fopen( $lockname, ‘w’ );
// write the username of the current user in the lockfile
fclose( $fh );

// Open the file for editing
// Do all the editing here
// Close the file for editing

// If you're done you want to give the file free again
$finished = $_REQUEST['finished'];
if ( $finished )
{   unlink( $lockname );
}

}
[/php]

With this method you’d have to train your users to close files though, if they walk away halfway through an edit and never return you or another administrator will have to throw away the lockfiles.

(N.B. this way the files can be locked over multiple client-server-client interactions, if that’s not what you seek unlink() the lockfile every time you edit and don’t wait for ‘finished’ to be sent. )

I hope this helps you,
Good luck!

O.

Sponsor our Newsletter | Privacy Policy | Terms of Service