在来自不同 PHP 线程的同一文件上运行 file_put_contents() 是否存在风险?

php
2022-08-30 15:19:25

我知道file_put_contents()使得在PHP中将数据附加到文件中变得非常容易。我想尝试使用PHP“线程”来访问来自不同PHP线程的同一日志文件。在来自不同 PHP 线程的同一文件上运行 file_put_contents() 是否存在风险,或者如果文件被锁定或被另一个线程访问,这些线程是否会愉快地阻塞?file_put_contents()

编辑:发现了一个类似的问题,建议flock(),但风险问题似乎没有得到充分解决。这些是“原子”写入操作吗?


答案 1

正如它在手册页上所说的那样(您提供了一个链接!

// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);

使用标志防止双重写入LOCK_EX


答案 2

答案很简单,是的。可能发生冲突

使用类似的东西file_put_contents($location, $data, FILE_APPEND | LOCK_EX);

当您期望多个实例写入同一文件时,您应该获取一个独占锁,以便在当前进程完成写入其数据之前,其他进程无法写入该文件


推荐