1

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?

giozh
  • 9,868
  • 30
  • 102
  • 183
  • I suggest to use database to avoid this issue. – dlyaza Apr 14 '14 at 09:56
  • i couldn't use db because i need to store large amount of data that db couldn't store (db could be ok in my case for small amount of data) EDIT: when i call that script, i'm the only one who ask lock on file – giozh Apr 14 '14 at 09:57

1 Answers1

3

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

Radu Diță
  • 13,476
  • 2
  • 30
  • 34