gpt4 book ai didi

php - 如何将 file_put_contents() 与 FILE_APPEND 一起使用 | LOCK_EX 安全吗?

转载 作者:可可西里 更新时间:2023-10-31 22:15:36 25 4
gpt4 key购买 nike

我正在使用:

file_put_contents("peopleList.txt", $person, FILE_APPEND | LOCK_EX);

写入文件末尾并确保没有其他人(或脚本)同时写入同一文件。

PHP manual表示如果不成功,它将返回一个假值。

如果它不能获得文件的锁,它会失败,还是继续尝试直到它可以?如果在无法获得锁的情况下确实失败,确保数据写入的最佳方法是什么?

也许在 while 循环中循环函数直到它不返回 false(畏缩)或者只是向用户(网站访问者)提供某种 GUI 以请求他们重试?

最佳答案

其实我之前的回答有点过时了。 flock() block 直到 requested lock is acquired :

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled (on non-Windows platforms) with the LOCK_NB option documented below.

既然 file_get_contents() 使用了它,我假设它是一样的。也就是说,请注意它因操作系统而异。

更重要的是,您不需要在您描述的场景中锁定文件,原因是 N.B.已经解释过了。除非您使用的是 CLI SAPI,否则我想不出您应该担心文件锁定的常见情况。

关于php - 如何将 file_put_contents() 与 FILE_APPEND 一起使用 | LOCK_EX 安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9009058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com