You want 'r+' (or c+ if using a newer version of PHP). r+ does not truncate (does not do c+ ), but still allows you to write.
here is an excerpt from the last time I worked with these functions:
/* if file exists, open in read+ plus mode so we can try to lock it -- opening in w+ would truncate the file *before* we could get a lock! */ if(version_compare(PHP_VERSION, '5.2.6') >= 0) { $mode = 'c+'; } else { //'c+' would be the ideal $mode to use, but that only //available in PHP >=5.2.6 $mode = file_exists($file) ? 'r+' : 'w+'; //there a small chance of a race condition here // -- two processes could end up opening the file with 'w+' } //open file if($handle = @fopen($file, $mode)) { //get write lock flock($handle,LOCK_EX); //write data fwrite($handle, $myData); //truncate all data in file following the data we just wrote ftruncate($handle,ftell($handle)); //release write lock -- fclose does this automatically //but only in PHP <= 5.3.2 flock($handle,LOCK_UN); //close file fclose($handle); }
source share