PHP Simultaneous File Writes

后端 未结 5 1779
后悔当初
后悔当初 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:41

    Please note:

    As of PHP 5.3.2, the automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

    The updated backward compatible code is:

    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);
    }
    

    i.e. you have to call flock(.., LOCK_UN) explicitly because fclose() does not do it anymore.

提交回复
热议问题