PHP Simultaneous File Writes

Ama*_*wal 20 php file-io file

I have two different PHP files that both write to the same file. Each PHP script is called by a user action of two different HTML pages. I know it will be possible for the two PHP files to be called, but will both PHP files attempt to write to the file at the same time? If yes, what will happen? Also, it is possible to make one of the PHP fail gracefully (file write will just fail, and the other PHP can write to the file) as one PHP function is less important that the other.

cha*_*aos 32

解决此问题的常用方法是将两个脚本flock()用于锁定:

$f = fopen('some_file', 'a');
flock($f, LOCK_EX);
fwrite($f, "some_line\n");
flock($f, LOCK_UN);
fclose($f);
Run Code Online (Sandbox Code Playgroud)

这将导致脚本在写入之前等待彼此完成文件.如果你愿意,"不太重要"的脚本可以做到:

$f = fopen('some_file', 'a');
if(flock($f, LOCK_EX | LOCK_NB)) {
    fwrite($f, "some_line\n");
    flock($f, LOCK_UN);
}
fclose($f);
Run Code Online (Sandbox Code Playgroud)

这样如果发现某些东西忙于文件就不会做任何事情.


Ant*_*ult 11

请注意,如果文件作为追加打开,则posix表示原子访问.这意味着您可以使用多个线程附加到该文件,并且它们的行不会被破坏.

我用十几个线程和几十万行测试了这个.没有一行被破坏.

这可能不适用于超过1kB的字符串,因为buffersize可能超过.

这可能也不适用于不符合posix标准的Windows.


Mar*_*cio 9

请注意:

从PHP 5.3.2开始,删除了文件资源句柄关闭时的自动解锁.现在解锁总是必须手动完成.

更新的向后兼容代码是:

if (($fp = fopen('locked_file', 'ab')) !== FALSE) {
    if (flock($fp, LOCK_EX) === TRUE) {
        fwrite($fp, "Write something here\n");
        flock($fp, LOCK_UN);
    }

    fclose($fp);
}
Run Code Online (Sandbox Code Playgroud)

即你必须明确调用flock(..,LOCK_UN)因为fclose()不再这样做了.