PHP: file_get_contents/file_put_contents you can lose data!

As I have written in this article:

And prooved buffering by this tests on remote server:
Do not use this functions when you modify the file you are working with. Either use fflock, fread, fflush, ffwrite work-around or you can lose your data when you use file_get_contents/file_put_contents.

The reason why there is no mention about it on internet is that most programmers of website use databases for purposes of data modifications (instead of files).

Another interesting article about atomicity is at Czech (also read slovak comments). There are some interesting solution. This is also about non-atomic file solutions. But there is also mention that the file can be opened between fopen and flock, which explains why in my stests T5-T7 there were these problems. Read the article at English or translate it. Mr. Vrana also has a cool solution of page caching.

Read this:

There's the problem of calling fopen and then flock. Between these two operations (at least I think), another instance of the script can enter and open that file (for reading). If the original fopen was opened for writing, you probably lose the data in that file.
Read Jakub Vrána:

Probability increases with the number of processes working on the same task, which I write in the article. This is unrelated to PHP's intelligence - the operating system determines which process is going to be the turn - at any time it can remember that it will give the opportunity to another process.

Komentáře

Oblíbené příspěvky