Using:
fopen
fwrite
fclose
What happens if two users attempt to open the same file at the same time?
Small-scale file operations are so quick that two writes at the exact same time are fairly rare. Regardless, you can use flock
to lock the file:
$fp = fopen('file.log', 'a+');
flock($fp, LOCK_EX);
fwrite($fp, 'my data');
flock($fp, LOCK_UN);
fclose($fp);
Note fclose
automatically unlocks the file, but the I find it makes the code a little more user-friendly to put these things in.
What is important is:
The classic example is the Cash machine/bank balance example used in many texts.
Any kind of shared writable state requires some form of concurrent access control such as a mutex, but there are tons of potential problems such as race conditions, starvation and variations on the dining philosophers problem.
Many operating systems however allow File locking of some description, which means the other process waits for the lock to be released. See PHP's flock() for locking a file.
You can also use a "checkout, change, commit/merge" approach.
Depending on your reasons, you may want to consider a database such as MySQL or SQLite as these will provide faster, more robust ways to share state which is read-heavy or cache-less.
The numerous problems, pitfalls and ways of sharing state is vast. Apologies for all the Wikipedia usage.
Use file_put_contents()
instead with the FILE_APPEND
or LOCK_EX
flags.
Any of these flags lock the file for writing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With