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

标签 php flock

我已经阅读了 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/

相关文章:

php - htaccess 仅在未提供参数的情况下将一个域重定向到另一个域?

javascript - colpick 不适用于 .html 到 .php 扩展名更改

multithreading - 锁定 Perl 子例程

bash - flock 是否理解多个 bash 命令的 && 命令?

javascript - 如何从javascript获取数据

php - 对于 PHP PayPal API,我需要使用哪种付款方式?

perl - 涌入 Perl : Bad file descriptor

python - python 的 fcntl.flock 函数是否提供文件访问的线程级锁定?

php - 如何在使用 LEFT JOIN 和 GROUP BY 时显示不同列的总值

php - 为什么我的文件在尝试使用 PHP 读取时总是为空?