title: What's the best way to read from and then overwrite file contents in php?
body: <p>What's the cleanest way in php to open a file, read the contents, and subsequently overwrite the file's contents with some output based on the original contents?  Specifically, I'm trying to open a file populated with a list of items (separated by newlines), process/add items to the list, remove the oldest N entries from the list, and finally write the list back into the file.</p>
  
  <pre><code>fopen(&lt;path&gt;, 'a+')
  flock(&lt;handle&gt;, LOCK_EX)
  fread(&lt;handle&gt;, filesize(&lt;path&gt;))
  // process contents and remove old entries
  fwrite(&lt;handle&gt;, &lt;contents&gt;)
  flock(&lt;handle&gt;, LOCK_UN)
  fclose(&lt;handle&gt;)
  </code></pre>
  
  <p>Note that I need to lock the file with flock() in order to protect it across multiple page requests.  Will the 'w+' flag when fopen()ing do the trick?  The php manual states that it will truncate the file to zero length, so it seems that may prevent me from reading the file's current contents.</p>