PHP and concurrent file access

后端 未结 4 1288
我在风中等你
我在风中等你 2020-12-14 22:28

I\'m building a small web app in PHP that stores some information in a plain text file. However, this text file is used/modified by all users of my app at some given point i

4条回答
  •  借酒劲吻你
    2020-12-14 22:49

    You should put a lock on the file

        $fp = fopen("/tmp/lock.txt", "r+");
    
    if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
        ftruncate($fp, 0);      // truncate file
        fwrite($fp, "Write something here\n");
        fflush($fp);            // flush output before releasing the lock
        flock($fp, LOCK_UN);    // release the lock
    } else {
        echo "Couldn't get the lock!";
    }
    
    fclose($fp);
    

    Take a look at the http://www.php.net/flock

提交回复
热议问题