3

I'm using file() to read through a file like an array with tabs. I want to lock the file but I cannot seem to get flock() working on the file. Is it possible to do this? If so, how? If not, does the file() lock the file from the start and alleviate any potential sharing problems?

Mr Brimm
  • 133
  • 2
  • 12
  • Can you provide a sample of your code to describing what do you want to achieve here? and what filesystem do you use? – Gajahlemu Jan 25 '11 at 02:08

1 Answers1

4

According to the documentation (specifically the comments), it won't read a file that was locked via flock.

You have 2 alternatives.

  1. Read the file with fgets (without checks for errors):

    $f = fopen($file, 'r');
    flock($f, LOCK_SH);
    $data = array();
    while ($row = fgets($f)) {
        $data[] = $row;
    }
    flock($f, LOCK_UN);
    fclose($f);
    
  2. Read the file with file() and using a separate "lockfile":

    $f = fopen($file . '.lock', 'w');
    flock($f, LOCK_SH);
    $data = file($file);
    flock($f, LOCK_UN);
    fclose($f);
    unlink($file . '.lock');
    
ircmaxell
  • 163,128
  • 34
  • 264
  • 314