Does file () write when reading?

I use file () to read a file, such as a tabbed array. I want to lock the file, but I cannot get flock () to work with the file. Is it possible to do this? If so, how? If not, does file () block the file from the start and fix any sharing issues?

+3
source share
1 answer

According to the documentation (in particular, comments), he will not read the file that was blocked through flock.

You have 2 options.

  • Read the file with fgets(without checking for errors):

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

    $f = fopen($file . '.lock', 'w');
    flock($f, LOCK_SH);
    $data = file($file);
    flock($f, LOCK_UN);
    fclose($f);
    unlink($file . '.lock');
    
+4
source

Source: https://habr.com/ru/post/1787600/


All Articles