Mr Brimm
Mr Brimm

Reputation: 133

Does file() lock the file when reading?

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?

Upvotes: 3

Views: 2286

Answers (1)

ircmaxell
ircmaxell

Reputation: 165271

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');
    

Upvotes: 4

Related Questions