编程语言
首页 > 编程语言> > php的file_get_contents是否忽略文件锁定?

php的file_get_contents是否忽略文件锁定?

作者:互联网

我已经在’file_get_contents’函数上阅读了php的manual page,该函数没有说明有关’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

我这个说法正确吗?我运行了一些测试,排他地锁定文件并不断对其进行写入,同时在另一个php进程中使用file_get_contents读取文件,并且没有遇到如上所述的行为

file_get_contents() will return an empty string (like in “”)

一般来说,PHP的file_get_contents完全不关心咨询文件锁定是真的吗?
另外,我是否正确假设在file_get_contents返回的空字符串的网页中声明为空“”,仅当文件为空或临时为空(在修改时)为真,但通常不为空(仅针对文件被flock()的原因?

解决方法:

flock相对独立于文件操作,甚至可以在锁定的文件上使用fopen.作为开发人员,您需要在需要锁定的所有地方检查/使用群集.

但是是的,在这方面,file_get_contents确实没有内置方法来在读取文件时获取读取锁定.因此,解决方法将是必经之路.

file_put_contents允许您获得写入锁定.

标签:flock,php
来源: https://codeday.me/bug/20191109/2012350.html