Multiple users write to the same file at the same time using PHP

前端 未结 4 2019
挽巷
挽巷 2020-12-11 10:20

I have a website where at the same moment, there can be multiple users writing to the same file at the same time. An example of my code is below.

PHP 5.6

4条回答
  •  Happy的楠姐
    2020-12-11 10:37

    This is a common theoretical problem for many web applications in many programming languages.

    The answer is yes, it CAN cause trouble. However, this is a very theoretical problem, if the contents you are adding to the files aren't very big and if you don't have heavy traffic. Today's operating systems and file systems are so well optimized (Caching, lazy writing etc.) that it is very unlikely to happen, when you close your file handles immediately after using them.

    You could add something like a buffer, if you run into an error (check access rights before writing with PHP/catch exceptions in other languages) and try again after some delay or write your buffer to a temp file and merge it with another process - you have several possibilities.

    And yes, flock() is a function that could be good for these purposes, but I think, that would be already over-engineered.

提交回复
热议问题