This article mainly introduces the PHP implementation of the file lock lock, unlock the operation of the method, combined with an example of the PHP file to lock, unlock the operation of the function, implementation methods and related considerations, the need for friends can refer to the next
In the project, the general use of logs, such as database query logs, access logs, external interface requests return parameter logs, in the processing of the log is simple as follows
$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 file lock resolves high concurrency
PHP file lock concurrency operation detailed
Example Analysis of PHP file lock and Process lock