For some reason you will not find this important information in manual, but if you need to access a file, modify it and then save it, so these functions are not suitable. You may lose your data. You were warned.
More information please follow the topic here:
PHP: Results of comparation file_get_contents & file_put_contents vs flock, fread, fflush, fwrite.
It is not a collision between these two functions, both atomic and reliable. The problem is if you read, modify, and save the file. These three actions are not in one transaction and therefore you may lose data when you overlap. If you need such a use case, use the database. (by Kit)
This means, that the functions are not suitable for many things like, saving users information (sign-up) to a file. You may do this with a carefull fopen, fflock (with LOCK_EX), fread, fclose, fopen (with LOCK_EX), fwrite, fclose and check the size after write. You need to check the size before write and after write but you need to clear the cache first: clearstatcache(); Then use filesize to get the correct size. Also count with the need to restore the file with copy(), if you find out that the size is incorrect. You need to do this manually if you don't want to use database.
You can see my benchmark tests which proofs, that the functions file_get_contents and file_put_contents use buffering, which means you do not have the correct data after you change your file. The functions will take the old copy of data from buffer, not the current data from disk (they will even not write the change data to disk). So yes, these functions are super fast, but for some operations they are not usable.
Žádné komentáře:
Okomentovat