PHP flock() Function
Definition and Usage
The flock() function locks or unlocks a file.
Returns true on success. Returns false on failure.
Syntax
flock(file,lock,block)
Parameter | Description |
---|---|
file | Required. Specifies the opened file to be locked or unlocked. |
lock | Required. Specifies which locking type to use. |
block | Optional. If set to 1 or true, it will block other processes when locking. |
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 prior to PHP 4.0.1).
- To obtain an exclusive lock (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).
Tips and Comments
Tip:Can be used fclose() To release the locking operation, the code will also automatically call when the execution is completed.
Note: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).
Example
<?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); ?>