title: PHP Lock file while reading - flock() makes my file blank
body: <p>As you can see in the code below, I'm trying to use flock to prevent other clients to acess the php (actually multiple users will acess this something like 10 times per second, each one), as I've found searching here... But this is not working. My data.txt is getting blank everytime doing this.</p>
  
  <pre><code>&lt;?php
  $fileName = $_GET["room"]."/data.txt";
  
  function replaceLine($data){
      if (stristr($data, $_GET["player"])){
          return $_GET["player"]." ".$_GET["data"]."\n";
      } 
      return $data;
  }
  
  $file = fopen($fileName,"r");
  
  if (flock($file, LOCK_EX)){
      //ftruncate($file, 0);
      ///--------------
  
      $data = file($fileName);
      $data = array_map("replaceLine", $data);
      file_put_contents($fileName, implode('', $data));
  
      echo fread($file, filesize($fileName)+1);
  
      ///--------------
      fflush($file);
      flock($file, LOCK_UN);
  } else {
      echo "wait";
  }
  
  fclose($file);
  
  ?&gt;
  </code></pre>
  
  <p>This is the original code (that I was trying to modify to prevent making the file empty): (It works as I want, but have this file problem...)</p>
  
  <pre><code>&lt;?php
  $fileName = $_GET["room"]."/data.txt";
  
  function replaceLine($data){
      if (stristr($data, $_GET["player"])){
          return $_GET["player"]." ".$_GET["data"]."\n";
      } 
      return $data;
  }
  
  $data = file($fileName);
  $data = array_map("replaceLine", $data);
  file_put_contents($fileName, implode('', $data));
  
  $file = fopen($fileName,"r");
  echo fread($file, filesize($fileName)+1);
  fclose($file);
  
  ?&gt;
  </code></pre>
  
  <p>Sorry for asking this newbie question, but I have not idea how to fix this and I'm searching and trying different things for weeks! Thanks!</p>