In the project, the general use of the log, such as database query log, access logs, external interface request return parameter log, this article and we have to implement the PHP file lock lock, unlock the method of operation, combined with an example of PHP for file lock, unlock the function of the operation, Implementation methods and related considerations, the need for friends can refer to, hope to help everyone.
$file = ' Log.txt '; $fp = fopen ($file, ' A + '), if (!is_writable ($file)) {die ("The $file are not writable!");} Fwrite ($fp, ' here '); fclose ($FP);
But this type of writing is flawed, a site is not only one user access at the same time, when more than one user access, there will be a problem, that is, when multiple processes use the same resource, the previous process wrote half the process behind the start of writing, so the last generation of the log is a mess. In this case, the lock is used, during the file lock, other processes will not modify the file, only when the file is unlocked, can be manipulated. The wording is as follows
$file = ' Log.txt '; $fp = fopen ($file, ' A + '), if (!is_writable ($file)) { exit ("The $file is not writable!");} Flock ($FP, LOCK_EX);//Locking Fwrite ($fp, ' here '); Flock ($fp, lock_un);//Unlock fclose ($FP);
If you want to test under the file lock during the other process can not manipulate the file example, you may use the demo shown below
log.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 '); Flock ($fp, Lock_un); fclose ($FP);
test.php
$file = ' Lock.txt '; $fp = fopen ($file, ' a '); Fwrite ($fp, ' good '); Fclose ($FP) is not written during sleep;//or directly using the example below, it is found that printing is a null value//var_dump (file_get_contents ($file)) during sleep;
When testing, run log.php first, and then run test.php, you will find that during sleep, the test.php is not performed to achieve the effect.
Related recommendations:
PHP with lock to achieve the concurrent snapping function
How to implement the MySQL statement lock
MySQL high concurrency plus lock transaction processing