Allow 1 access at a time using fopen()

Viewed 28

I'd like to allow 1 access at a time to a .txt file until the script finishes, so that it shows the message "Busy" when I open the same PHP again.

I have tried this:

<?php
$file = fopen('file.txt', 'w+');
if (flock($file, LOCK_EX)) {sleep(60); flock($file, LOCK_UN);}
else {echo 'Busy';}
fclose($file);

However it never shows the "Busy" message. Every new tab I open is in "sleep" mode. What am I doing wrong?

1 Answers

The documentation for flock is extremely poor.

As stated in the top comment:

If the file has been locked with LOCK_EX in another process, the CALL WILL BLOCK UNTIL ALL OTHER LOCKS have been released.

The result of this is, you will always be blocking on the call to flock. Your else clause would only execute if there is some error that prevents the file lock from being created - not when the file is already locked.

Related