This article mainly introduces how to use flock to implement file lock in PHP. The example analyzes the usage skills of flock file lock. For more information, see
This article mainly introduces how to use flock to implement file lock in PHP. The example analyzes the usage skills of flock file lock. For more information, see
This article describes how PHP uses flock to implement File Locking. Share it with you for your reference. The specific analysis is as follows:
Flock () allows you to execute a simple read/write model (including most Unix-derived versions and even Windows) that can be used on any platform ). If the lock is blocked (in case of EWOULDBLOCK error code), set the third optional parameter to TRUE. The lock operation can also be released by fclose () (automatically called when the code is executed ).
To put it simply, it is to lock a file so that multiple processes are limited to access the file, thus 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) ;?>
Note:
The ghost file is exclusively locked (this file can only be read and written by this user). If other new users want to access this file, it will be blocked ,, until the former closes the file (release lock ).
2. if you change the code to flock ($ file, LOCK_EX + LOCK_NB), an Error is returned directly when the lock is triggered. If a new user accesses the file, an Error locking file is output!"
3. the syntax of this function is flock (file, lock, block), where file is required. Specifies the opened files to be locked or released. Lock is required. Specifies the type of lock to be used. Optional. If it is set to 1 or true, other processes are blocked when the lock is performed.
For example, write a PHP code to ensure that multiple processes write data to the same file 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 help you with php programming.