Home > Article > Backend Development > file - php file locking
As shown in the picture, when I run two scripts at the same time, why can the second script write to the file immediately? Isn’t the file locked in the first script?
As shown in the picture, when I run two scripts at the same time, why can the second script write to the file immediately? Isn’t the file locked in the first script?
PHP reading and writing files are locked. For details, please refer to this http://www.jb51.net/article/81246.htm
Your second fwrite is operated without applying for the exclusive lock LOCK_EX before, and of course it will be written.
You must apply for LOCK_EX before both fwrites, so that it can have a locking effect.
<code>foo1.php: <?php header('Content-Type: text/plain; charset=utf-8'); if(file_exists('arr.php')) { $arr = require 'arr.php'; //先require后fopen } else { file_put_contents('arr.php','<?php return array();'); } $fp = fopen('arr.php', 'r+'); //读写方式打开,将文件指针指向文件头 if(flock($fp,LOCK_EX)) { //阻塞到获取排它锁 $arr['name'] = __FILE__; ftruncate($fp, 0); //截断文件 fwrite($fp,'<?php return '.var_export($arr, true).';'); var_export($arr); fflush($fp); //在释放锁之前刷新输出 sleep(10); //睡眠10秒,在此期间访问foo2.php将被阻塞 flock($fp, LOCK_UN); //释放锁定 } fclose($fp); foo2.php: <?php header('Content-Type: text/plain; charset=utf-8'); $arr = require 'arr.php'; $fp = fopen('arr.php', 'r+'); if(flock($fp,LOCK_EX)) { $arr['name'] = __FILE__; ftruncate($fp, 0); fwrite($fp,'<?php return '.var_export($arr, true).';'); var_export($arr); fflush($fp); flock($fp, LOCK_UN); } fclose($fp);</code>