$file = 'log.txt';
$fp = fopen($file, 'a+');
if(!is_writable($file)){
die("The $file is not writable!");
}
fwrite($fp, 'here');
fclose($fp);但这种写法是由瑕疵的,一个网站同一时间并不是只有一个用户访问的,在多个用户同时访问时,就会出现问题,也就是多个进程使用同一个资源时,前一个进程写到一半后面的进程便开始写了,因此最后生成的日志就乱了。这种情况下,就用到锁了,在文件加锁期间,其他进程是不会修改文件的,只有当文件解锁时,才可以操作。写法如下
$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);如果想测试下在文件加锁期间其他进程操作不了文件的例子,可以用下面给出的demo
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(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));
测试时,先运行log.php,再运行test.php,会发现在sleep期间,test.php是执行达不到效果的。
| 欢迎光临 一起源码网 (https://www.171739.xyz/) | Powered by Discuz! X3.3 |