Kursrekommendation:

PHP flock() funktion

Definition och användning

flock() funktionen låser eller frigör filer.

Självklart. Returnerar true om framgång, annars false.

flock(file,lock,block)
Parameter Beskrivning
file Obligatorisk. Anger vilken öppen fil som ska låsas eller frigå.
lock Obligatorisk. Anger vilket låstyp som ska användas.
block Valgfritt. Om satt till 1 eller true, blockeras andra processer vid låsning.

Description

The operation of flock() file It must be a file pointer that has already been opened.

lock The parameter can be one of the following values:

  • To acquire shared locking (reading program), set lock to LOCK_SH (set to 1 in versions prior to PHP 4.0.1).
  • To acquire exclusive locking (writing program), set lock to LOCK_EX (set to 2 in versions prior to PHP 4.0.1).
  • To release the lock (whether shared or exclusive), set lock to LOCK_UN (set to 3 in versions prior to PHP 4.0.1).
  • If you do not want flock() to block during locking, set lock Add LOCK_NB (set to 4 in versions prior to PHP 4.0.1).

提示和注释

提示:It can be done through fclose() To release the locking operation, the code will also automatically call when the execution is completed.

注释:Since flock() requires a file pointer, it may be necessary to use a special locking file to protect access to the file intended to be opened in write mode (add "w" or "w+" in the fopen() function).

实例

<?php
$file = fopen("test.txt","w+");
// exclusive locking
if (flock($file,LOCK_EX))
  {
  fwrite($file,"Write something");
  // release lock
  flock($file,LOCK_UN);
  }
else
  {
  echo "Error locking file!";
  }
fclose($file);
?>