This article describes the example of PHP using flock to implement file locking. Share it with everyone for your reference. The specific analysis is as follows:
Flock is explained in the official documentation: flock() allows you to implement a simple read/write model that can be used on any platform (including most Unix derivatives and even Windows). If the lock will block (in case of EWOULDBLOCK error code), set the optional third parameter to TRUE. Lock operations can also be released by fclose() (also called automatically when the code completes execution).
To put it simply, it is to lock a file so that multiple processes are restricted from accessing the file, thereby preventing conflicts. For 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. The meaning of this code is to open the file test.txt in read and write mode. When a user calls the php page, that is, the test.txt file is operated, then flock($file,LOCK_EX ) code, which will exclusively lock the test.txt file (the file can only be read and written by this user), then if any other new user wants to access the file, it will be blocked until the former closes the file (releases the lock) .
2. If the code is changed to flock($file,LOCK_EX LOCK_NB), it means that an error is returned directly when locking. Then if a new user accesses the file, "Error locking file!" will be output.
3. The syntax of this function is flock(file,lock,block), where file is required. Specifies an open file to be locked or released. lock required. Specifies which lock type to use. block is optional. If set to 1 or true, blocks other processes while locking.
For example: Please write a piece of PHP code to ensure that multiple processes can write the same file successfully at the same time
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; }
I hope this article will be helpful to everyone’s PHP programming design.