Lock's interpretation in the official documentation is that flock () allows you to perform a simple read/write model that can be used on any platform (including most Unix-derived versions and even Windows). If the lock is blocked (ewouldblock error code case), set the optional third parameter to TRUE. The lock operation can also be released by Fclose (), which is also automatically called when the code is finished executing.
In simple terms, locking a file allows multiple processes to restrict access to the file, preventing collisions. As an example:
<?php $file = fopen ("Test.txt", "w+"); if (Flock ($file, lock_ex)) {fwrite ($file, "Write something"); Flock ($file, lock_un); } else {echo "Error locking file!"; } fclose ($file);?>
Description
1. This code means to open the file Test.txt read-write, when a user invokes the PHP page, that is, the Test.txt file, then the flock ($file, LOCK_EX) code is executed, An exclusive lock on the Test.txt file, which can only be read and written by the user, is blocked if another new user wants to access the file, until the file is closed (release lock).
2. If the code is changed to flock ($file, LOCK_EX+LOCK_NB) to indicate that the error is returned directly when locked, then the "Error locking file!" will be output if a new user accesses the file
Code Academy PHP Tutorial _ Code Academy
3. The syntax of the function is flock (file,lock,block), where file is required. Specifies the open files to lock or release. Lock required. Specifies which type of lock to use. Block is optional. If set to 1 or true, the other process is blocked when the lock is made.
function WriteData ($path, $mode, $data) {$fp = fopen ($path, $mode); $retries = 0; $max _retries = 100; do{if ($retries > 0) {usleep (rand (1, 10000)); } $retries + = 1; }while (!flock ($FP, LOCK_EX) and $retries <= $max _retries); if ($retries = = $max _retries) {return false; } fwrite ($fp, "$data \ n"); Flock ($FP, lock_un); Fclose ($FP); return true; }
PHP uses flock to implement file lock to prevent multiple processes from writing to files at the same time