Skip to content
Advertisement

PHP file processing, possible data corruption

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement