1

I have a file composed of 3 rows. The first row is a string of data. The second is a number and the third is another number.

There are two PHP scripts running at the same time. The first is writing data in the first and third rows. The second is writing data in the second row and is reading the first row.

Can this cause data corruption, since the two scripts are never writing in the same place?

4
  • Why don't you make 3 different files? If you want to stay with this approach instead of using databases Commented Jul 6, 2021 at 8:59
  • @the_nuts You're right, this is definitely what I'll do Commented Jul 6, 2021 at 9:28
  • Wouldn't that still leave you with at least one file that can potentially get read and written at the same time? Commented Jul 6, 2021 at 12:19
  • @Gordon It does, but since it's two different actions, it does not seem to be a problem. I tested with 512ko of data being constantly read and write at the same time every 1ms, for 2min. There wasn't any data corruption. Don't know how PHP operates, but it seems pretty robust. Commented Jul 6, 2021 at 12:27

1 Answer 1

1

If Script A writes data into the first row while Script B is currently reading it, you might indeed end up with corrupted data for that line. The chances of that happening depends on the frequency of these operations. It's likely slim. But in theory, this could happen.

The easiest way to protect against that is to use

Your script writing to the file has to acquire an exclusive lock when it wants to write to the file. Your script reading the file will have to check whether the file is currently locked. If it is, the script can wait for the file to be released again.

Note that this approach assumes that the file will only ever be changed by these two PHP scripts.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.