Fopen, fread and flock

I need to lock the file, read the data, write to the file and then close it. The problem that I have is, I'm trying to find the correct mode for fopen.

With 'a +' - always add data, while 'w +' truncates all data when opened with 'x +' - the file cannot be locked.

This is my code:

$fh_task = fopen($task_file, 'w+'); flock($fh_task, LOCK_EX) or die('Cant lock '.$task_file); $opt_line = ''; while(!feof($fh_task)){ $opt_line .= fread($fh_task, 4096); } $options = unserialize($opt_line); $options['procceed']++; rewind($fh_task); fwrite($fh_task, serialize($options)); flock($fh_task, LOCK_UN); fclose($fh_task); 
+4
source share
3 answers

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); } 
+7
source

I believe you want c+ . This is similar to r+ , except that it will create a file that does not exist. If you do not want to do this, use r+ instead. After opening the file, use flock() as needed. You can c+ open to read and write. Other than that, I think you can use the same code.

Another answer is correct, but they use an extra step to determine if r or w is used when c does this automatically.

+2
source

Frank Farmer code is no better than yours. Between file_exists and fopen, another process can perform its own file manipulations.

Create a semaphore file before opening the "task" file.
Sort of:

 if (($f_sem = @fopen($task_file.'.sem', 'x'))) { //your code (with flock) fclose($f_sem); unlink($task_file.'.sem'); } 
0
source

All Articles