Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jaynarayan's avatar

Need help to understand flock() of core php.

why $r is not false?

$fileHandle = fopen('mylines.txt','r+');
flock($fileHandle,LOCK_EX);
$r = file_put_contents('mylines.txt','should return false');
var_dump($r);
0 likes
3 replies
ApexLeo's avatar

@jaynarayan instead of file_put_contents why don't u use fwrite.

like this example



<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here\n");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

?>

hope that help

jaynarayan's avatar

Actually I am trying to fail the file_put_contents() for learning purposes. If the file is locked by another process ,file_put_contents() will return false. I have locked file using flock() so it shouldn't be accessible by file_put_contents() until I call fclose() or script ends.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

But you have locked it by the same process. Those 4 lines are all part of the same process.

Please or to participate in this conversation.