title: fopen(file,w+) truncates the file before I can check if it's locked with flock()
body: <p>I have a function which receives a filename and a json object to write to a text file. </p>
  
  <p>The object is updated and needs to entirely replace the current contents of the file. Each site visitor has their own file. Multiple rapid changes create a situation where the file is truncated by <code>fopen(file,w+)</code>, then not written to as it's locked. End result is empty file. </p>
  
  <p>I'm sure there's a standard simply way to do this as it's such a usual activity. Ideally what I'm looking for is a way to check if a file has a lock before truncating the file with <code>fopen</code> in <code>w+</code> mode or a way to switch modes. </p>
  
  <p>It seems strange that you would have to truncate the file with <code>fopen()</code> to get a file handle to pass to <code>flock()</code> to check if it's locked -- but you just truncated it, so what's the point?</p>
  
  <p>Here's the function I have so far:</p>
  
  <pre><code>function updateFile($filename, $jsonFileData) {
      $fp = fopen($filename,"w+");
      if (flock($fp, LOCK_EX)) {  
          fwrite($fp, $jsonFileData);
          flock($fp, LOCK_UN);
          fclose($fp);
          return true;
      } else {
          fclose($fp);
          return false;
      }
  }
  </code></pre>