In the project, generally use the log, such as database query log, access log, external interface request return parameter log, in the process of writing the log is as follows
$file = ' Log.txt ';
$fp = fopen ($file, ' A + ');
if (!is_writable ($file)) {
die ("The $file is not writable!");
Fwrite ($fp, ' here ');
Fclose ($FP);
But the wording is flawed, a Web site at the same time is not only one user access, the simultaneous access to multiple users, there will be problems, that is, multiple processes using the same resource, the previous process to write half of the process began to write, so the last generated log is chaotic. In this case, the lock is used, during the file lock, the other process will not modify the file, only when the file unlock, you can operate. Written as follows
$file = ' Log.txt ';
$fp = fopen ($file, ' A + ');
if (!is_writable ($file)) {
exit ("The $file is not writable!");
Flock ($FP, LOCK_EX);//Lock
fwrite ($fp, ' here ');
Flock ($FP, lock_un);//Unlock
fclose ($fp);
If you want to test examples of other processes that cannot manipulate files during file locking, you can 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 ');
Sleep (a);
Flock ($FP, lock_un);
Fclose ($FP);
test.php
$file = ' lock.txt ';
$fp = fopen ($file, ' a ');
Fwrite ($fp, ' good '); Not to be written during sleep
fclose ($fp);
Or use the following example directly to find out that printing is a null value
//var_dump (file_get_contents ($file) during sleep;
When testing, run log.php first, then run test.php, you will find that during sleep, test.php is performed without effect.