Home > Article > Backend Development > How to lock and unlock files in PHP
In projects, logs are generally used, such as database query logs, access logs, and external interface request return parameter logs. This article mainly introduces you to the method of locking and unlocking file locks in PHP, combined with examples. This form analyzes the functions, implementation methods and related precautions of PHP for file locking and unlocking operations. Friends who need it can refer to it. I hope it can help everyone.
$file = 'log.txt'; $fp = fopen($file, 'a+'); if(!is_writable($file)){ die("The $file is not writable!"); } fwrite($fp, 'here'); fclose($fp);
But this way of writing is flawed. A website is not only visited by one user at the same time. When multiple users visit it at the same time, problems will occur. That is, when multiple processes use the same resource, the previous process will start writing halfway before the subsequent process starts writing, so the final log generated will be messed up. In this case, locks are used. During the file locking period, other processes will not modify the file. They can only operate when the file is unlocked. The writing method is as follows
$file = 'log.txt'; $fp = fopen($file, 'a+'); if(!is_writable($file)){ exit("The $file is not writable!"); } flock($fp, LOCK_EX);// 加锁 fwrite($fp, 'here'); flock($fp, LOCK_UN);// 解锁 fclose($fp);
If you want to test the example where other processes cannot operate the file during the file locking period, you can use the demo
log given below. php
$file = 'log.txt'; $fp = fopen($file, 'a+'); if(!is_writable($file)){ exit("The $file is not writable!"); } flock($fp, LOCK_EX); fwrite($fp, 'here'); sleep(10); flock($fp, LOCK_UN); fclose($fp);
test.php
$file = 'lock.txt'; $fp = fopen($file, 'a'); fwrite($fp, 'good'); // 在sleep期间写不进去 fclose($fp); // 或是直接使用下面的这个例子,发现在sleep期间打印是个空值 //var_dump(file_get_contents($file));
When testing, run log.php first and then test.php , you will find that during sleep, test.php cannot be executed to achieve the effect.
Related recommendations:
PHP implements concurrent snap-up function through locking
Method to implement MySQL statement locking
Mysql High Concurrency Locking Transaction Processing
The above is the detailed content of How to lock and unlock files in PHP. For more information, please follow other related articles on the PHP Chinese website!