agaggi agaggi - 1 year ago 88
PHP Question

php flock behaviour when file is locked by one process

It could be answered somewhere but i am unable to find so asking here.

Lets consider a sample php script which deletes a line by user input

$DELETE_LINE = $_GET['line'];
$out = array();
$data = @file("foo.txt");
{ foreach($data as $line) if(trim($line) != $DELETE_LINE) $out[] = $line;
$fp = fopen("foo.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) fwrite($fp, $line);
flock($fp, LOCK_UN);

I want to know if some user is currently executing this script and file "foo.txt" is locked, in same time or before completion of its execution, if some other user calls this script, then what will happen ?
Will second users process wait for unlocking of file by first users? or line deletion by second users input will fail ?

Answer Source

If you try to acquire an exclusive lock while another process has the file locked, your attempt will wait until the file is unlocked. This is the whole point of locking.

See the Linux documentation of flock(), which describes how it works in general across operating systems. PHP uses fcntl() under the hood so NFS shares are generally supported.

There's no timeout. If you want to implement a timeout yourself, you can do something like this:

$count = 0;
$timeout_secs = 10; //number of seconds of timeout
$got_lock = true;
while (!flock($fp, LOCK_EX | LOCK_NB, $wouldblock)) {
    if ($wouldblock && $count++ < $timeout_secs) {
    } else {
        $got_lock = false;
if ($got_lock) {
    // Do stuff with file
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download