php: exclusive lock on file never obtained
Question
On my php script, after parse a string, i need to write some data into a file (after create it if doesn't exist). Before write file, i need exclusive lock for avoid problems. This is my code:
foreach ($elements[0] as $current) {
$file_handler = fopen($my_folder . "/" . $current . ".txt", "a");
$locked = flock($file_handler, "LOCK_EX");
while (!$locked) {
usleep(500000);
$locked = flock($file_handler, "LOCK_EX");
}
//got lock
fwrite($file_handler, $mystring . "\n");
//release lock
flock($file_handler, LOCK_UN);
fclose($file_handler);
}
return;
Now, something seems not work. fopen create file, but my code seems go in loop inside while (file is created, but nothing was write inside). What's wrong?
Solution
You are passing the argument for locking as a string instead of a constant.
Try:
$locked = flock($file_handler, LOCK_EX);
Notice the missing double quotes around LOCK_EX
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow