title: php flock and fread and fwrite
body: <p>I see people using flock like this:</p>
  
  <pre><code>if (!$fp = fopen($file_name, 'wb'))  
  {  
      return FALSE;  
  }  
  
  if (flock($fp, LOCK_EX))  
  {  
      fwrite($fp, serialize($data));  
      flock($fp, LOCK_UN);  
  }
  </code></pre>
  
  <p>Also this:</p>
  
  <pre><code>if (!$fp = @fopen($file_name, 'rb'))  
  {  
      return FALSE;  
  }  
  
  flock($fp, LOCK_SH);  
  
  $data = '';  
  
  if (filesize($file_name) &gt; 0)  
  {  
      $data = unserialize(fread($fp, filesize($file_name)));  
  }  
  </code></pre>
  
  <p>But isn't there a chance that someone else will edit the file between the <code>fopen</code> call and the <code>flock</code> call? and the same question for <code>fread</code></p>
  
  <hr>
  
  <p>EDIT:<br>
  To clarify why I'm asking this... I'm basing my question on the code <a href="http://www.jongales.com/blog/2009/02/18/simple-file-based-php-cache-class/" rel="noreferrer"><strong>here,</strong></a> In a mysql caching situation, what's to stop 20 people from all being able to access the file at the same time if they all can get in between the fopen and flock?</p>
  
  <p>Is that code foolproof?</p>