Analysis of PHP File Lock Writing Instance

  • 2021-07-09 07:28:16
  • OfStack

This paper describes the writing method of PHP file with examples to deal with multi-thread writing. The specific code is as follows:


function file_write($file_name, $text, $mode='a', $timeout=30){ 
  $handle = fopen($file_name, $mode); 
  while($timeout>0){ 
    if ( flock($handle, LOCK_EX) ) { //  Exclusive locking 
      $timeout--; 
      sleep(1); 
    } 
  } 
  if ( $timeout > 0 ){ 
    fwrite($handle, $text.'\n'); 
    flock($handle, LOCK_UN); 
    fclose($handle); // Release lock operation 
    return true; 
  } 
  return false; 
}

Where the handle of the flock (int $handle, int $operation) function operation must be an open file pointer.

operation can be one of the following values:

To get the shared lock (read program), set operation to LOCK_SH (PHP before 4.0. 1 was set to 1).
To obtain an exclusive lock (written program), set operation to LOCK_EX (set to 2 in versions prior to PHP 4.0. 1).
To release the lock (whether shared or exclusive), set operation to LOCK_UN (set to 3 in versions prior to PHP 4.0. 1).
If you do not want flock () to block when locked, add LOCK_NB to operation (set to 4 in versions prior to PHP 4.0. 1).

In addition, fclose () is used to release the lock operation and is called when the code is finished.


Related articles: