The flock() function locks or releases a file.
If successful, the function returns TRUE. If it fails, returns FALSE.
flock(file,lock,block)
parameter | describe |
---|---|
file | Required. Specifies an open file to be locked or released. |
lock | Required. Specifies which lock type to use. Possible values: LOCK_SH - shared lock (reading program). Allow other processes to access the file. LOCK_EX - Exclusive lock (writing program). Prevent other processes from accessing the file. LOCK_UN - Release a shared or exclusive lock LOCK_NB - Avoid blocking other processes when locked. |
block | Optional. If set to 1, blocks other processes while locking. |
Note: These locks are only used within the current PHP process. If permissions allow, other processes can modify or delete a PHP-locked file.
Note: flock() is mandatory under Windows.
Tip: You can release the lock operation through fclose(), which will be called automatically when the script execution is completed.
<?php$file = fopen("test.txt","w+");// exclusive lockif (flock($file,LOCK_EX)) { fwrite($file,"Write something"); // release lock flock( $file,LOCK_UN); }else { echo "Error locking file!"; }fclose($file);?>