Συνάρτηση flock() PHP

Ορισμός και χρήση

Η συνάρτηση flock() αποκλείει ή απελευθερώνει αρχεία.

Εάν επιτυχής, επιστρέφει true. Αν αποτυχία, επιστρέφει false.

Γλώσσα

flock(file,lock,block)
Παράμετροι Περιγραφή
file Απαιτείται. Ορίζει το ανοιχτό αρχείο που θα αποκλειστεί ή θα απελευθερωθεί.
lock Απαιτείται. Ορίζει ποιο τύπο αποκλειστικής χρήσης θα χρησιμοποιηθεί.
block Επιλογή. Αν οριστεί σε 1 ή true, θα εμποδίζει άλλους διεργασίες κατά την αποκλειστική χρήση.

Description

The operation of 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).

Hints and Comments

Hint:Can be used fclose() To release the locking operation, the code will also be automatically called when the execution of the code is completed.

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

Instance

<?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);
?>