PHP Simultaneous File Writes

后端 未结 5 1789
后悔当初
后悔当初 2020-12-09 09:03

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 t

5条回答
  •  不知归路
    2020-12-09 09:30

    The usual way of addressing this is to have both scripts use flock() for locking:

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

    This will cause the scripts to wait for each other to get done with the file before writing to it. If you like, the "less important" script can do:

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

    so that it will just not do anything if it finds that something is busy with the file.

提交回复
热议问题