我已经阅读了 php 的 manual page关于“file_get_contents”函数,它没有说明“file_get_contents”在 php 文件锁定方面的行为方式。然而,在评论部分,用户 Chris 建议
file_get_contents does not normally respect PHP's flock locking, i.e. advisory locking.
You can workaround this with some extra code to request a shared lock, like...
<?php
$tmp = fopen($path, 'rb');
@flock($tmp, LOCK_SH);
$contents = file_get_contents($path);
@flock($tmp, LOCK_UN);
fclose($tmp);
?>
我测试成功了。我还测试了即使文件已被 flock()
锁定独家LOCK_EX
可以让另一个 php 进程通过 file_get_contents
读取文件正如评论所暗示的那样。
然而,这也是我询问信息的主要原因,我阅读了一个标题为 "Reading locked files in PHP" 的网页,它声称以下关于 file_get_contents
和文件锁定。
Reading a locked file with file_get_contents()
This is one the worst way to read a file while it is locked and modified, because:
- file_get_contents() will return an empty string (like in "")
- filesize() will return the actual number of bytes written to the file
我这个说法正确吗?我运行了一些测试,在使用 file_get_contents
时专门锁定一个文件并不断写入它在另一个 php 进程中读取文件并且没有遇到如上所述的行为
file_get_contents() will return an empty string (like in "")
一般来说,php 的 file_get_contents
是真的吗?不关心咨询文件锁定。
另外,我是否正确地假设网页中关于 file_get_contents 返回的空字符串的声明是空的“”,仅当文件为空或暂时为空(修改时)但通常不为空(仅适用于文件被 flock()
编辑的原因)?
最佳答案
flock 相对独立于文件操作,您甚至可以对锁定的文件使用 fopen。作为开发人员,您有责任在需要锁定的任何地方检查/使用 flock。
但是在这方面是的,file_get_contents
确实没有在读取文件时获取读取锁定的内置方法。因此,解决方法是可行的方法。
file_put_contents
允许您获得写入锁。
关于php - php 的 file_get_contents 是否忽略文件锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262971/