Home >Backend Development >PHP Tutorial >A brief discussion on php file lock
The content of this article is about a brief discussion of PHP file locks. It has certain reference value. Now I share it with everyone. Friends in need can refer to it.
There is a difference between file locks in PHP and mysql table locks. The general usage is that only one person can operate it at the same time, so as to avoid the situation of multiple people operating the same file at the same time, which will lead to data loss. Let me introduce to you how to use PHP file lock.
The lock mechanism exists because of resource competition caused by concurrency. In order to ensure the effectiveness and integrity of operations, the concurrent state can be converted into a serial state through the lock mechanism. As one of the locking mechanisms, PHP's file lock is also designed to cope with resource competition. Assume an application scenario. In the case of large concurrency, fwrite is used to write data to the end of the file multiple times in an orderly manner. What will happen without locking? Multiple ordered write operations are equivalent to one transaction, and we need to ensure the integrity of this transaction at this time.
If we have two programs writing data to a file at the same time, in order to ensure the integrity of the data, we can add a file lock and let program 1 execute first. After program 1 is executed, unlock it and then Let program 2 execute. The implementation code is as follows:
$fp = fopen('test.txt',"a"); $count = 10; if (flock($fp, LOCK_EX)) { for($i=1;$i<$count;$i++){ fwrite($fp, 'text2_'.$i."rn"); echo "test2".date('h:i:s') . " "; sleep(1); echo "test2".date('h:i:s'); } flock($fp , LOCK_UN); }else{ echo "Couldn't lock the file !"; } fclose($fp);
Related recommendations:
PHP file locking ensures multi-threaded writing safety
The above is the detailed content of A brief discussion on php file lock. For more information, please follow other related articles on the PHP Chinese website!