Sunday, March 2, 2008

T tPHP: is there anyway to stop two scripts from writing to the same file the same time?

I have a text file on my server that is modified by a php page. Is it possible that if that page is accessed by two different people at the same time, the text file could get corrupted?

How can I stop more than one script from modifying the text file at the same time?

Answer on T tPHP: is there anyway to stop two scripts from writing to the same file the same time?

Sorry but it makes me smile as this kind of question is representative of people who have no background in development.

At least you figured the problem on your own. You need to implement a locking mechanism.

PHP gives you a very simple solution: flock()

Just be sure not to perform ANY file operations on the file before getting the lock or you may experience buffer inconsistencies. This limitation has caused me quite a bit of problems in a batch job I did as there is no way to prevent file buffering in PHP.