فункциة flock() في PHP

التعريف والاستخدام

فункциة flock() قفل أو إطلاق ملف.

إذا نجح، فإنه يعود إلى true. إذا فشل، فإنه يعود إلى false.

القواعد

flock(file,lock,block)
المعلمات وصف
file مطلوب. يحدد الملف المفتوح الذي سيتم قفله أو إطلاقه.
lock مطلوب. يحدد نوع القفل الذي سيتم استخدامه.
block اختياري. إذا تم تعيينه إلى 1 أو true، فإنه يمنع عملية أخرى عند القفل.

说明

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 obtain a shared lock (reading program), set lock to LOCK_SH (set to 1 in versions before PHP 4.0.1).
  • To obtain an exclusive lock (writing program), set lock to LOCK_EX (set to 2 in versions before PHP 4.0.1).
  • To release the lock (whether shared or exclusive), set lock to LOCK_UN (set to 3 in versions before PHP 4.0.1).
  • If you do not want flock() to block during locking, set lock Add LOCK_NB (set to 4 in versions before PHP 4.0.1).

提示和注释

提示:Can be used fclose() To release the locking operation, it will also be automatically called when the code 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);
?>