0

I am posting this not about code error but about possible conflict using this piece of code:

$logFile = 'data.log';
$result = (int) file_get_contents($logFile) + 1;
file_put_contents($logFile, $result);  

This will read a file called data.log and get it's number and write this number +1. But, I will run this application with many users calling this in realtime (like 100 users per second).

So, I want to know if this will create some conflict, get outupdated number and store wrong data or something like this. Is it possible? Are there an way to I avoid it?

Thank you.

1 Answers1

0

It will not work correctly because the data is not changed "atomically".

You can solve it by locking the file before accessing it - read about the flock function. But this could affect performance and possibly seriously limit your throughput - so you should benchmark it.

Generally speaking, this is not considered a "good" way to implement a counter. Look into using a proper database like MySQL or a NoSQL like MongoDB.

obe
  • 7,378
  • 5
  • 31
  • 40