PHP: flock and fwrite is not save, you can lose data

This is the same case as file_get_contents and file_put_contents. With all these functions you can lose data if multiple script are running same time, trying to read and write, esspecially write, the same file.

You can find some mentions here:

PHP flock() alternative

A locking file cache in PHP

I have made lots of tests using all possible methods:
1. file_get_contents/file_put_contents with LOCK_EX flag used in  T2-T3
2. fopen, fflock, fread, fclose, fopen, flock, fwrite, fflush, fclose in T5-T6
3. the same as in point 2, but without flock, using mkdir lock instead (T8, T9)

Please see the results here:

PHP: Results comparison of file_ (get) put_contents & f (read / write / flush)
The discussion in located on Czech server:

PHP: Výsledky srovnání funkcí file_(get)put_contents & f(read/write/flush)

So you can see clearly, that none of these methods is reliable, but - this is important - this is unders certain very rare circumstances. This test depends on how many circles you make and how many scripts you run. I run 4 scripts (made 1 script in real, but this runs after 4 requests were made from different browsers). So you may minimize the lock by descriting the number of the loops from 50 to 10 or 6 and you can do the same if you run only 3 scripts. Nobody will run such script in real, this was only to try simulate hard traffic. Of sure this is not the same as to run DOS attack using JS loop sending requests to server or some more realistic remote action.

Also please notice you have another articles regarding the atomicity on this blog, I have written them in English.

Komentáře

Okomentovat

Oblíbené příspěvky