Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use file_put_contents() with FILE_APPEND | LOCK_EX safety?

I'm using:

file_put_contents("peopleList.txt", $person, FILE_APPEND | LOCK_EX);

to write to the end of a file and to make sure no one else (or script) is also writing to the same file at the same time.

The PHP manual says it will return a falsy value if unsuccessful.

If it cannot obtain a lock on the file, will it fail or keep trying until it can? If it does fail when no lock can be obtained, what would be the best way to go about ensuring the data is written?

Perhaps looping the function in a while loop until it does not return false (cringe) or simply providing the user (website visiter) with some kind of GUI requesting they try again?

like image 542
hozza Avatar asked Jan 19 '12 14:01

hozza


People also ask

What is the difference between fwrite () and file_put_contents ()?

fwrite() allows to write to file a byte or block of bytes at a time, file_put_content() writes the entire file in one go.... which is better? depends what you need to do! and on the volumes of data that you want to write!

What is the use of file_put_contents?

The file_put_contents() writes data to a file. This function follows these rules when accessing a file: If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename. Create the file if it does not exist.

How can save file in specific folder in PHP?

php $target_Path = "images/"; $target_Path = $target_Path. basename( $_FILES['userFile']['name'] ); move_uploaded_file( $_FILES['userFile']['tmp_name'], $target_Path ); ?> when the file(image) is saved at the specified path... WHAT if i want to save the file with some desired name....

How do I overwrite a file in PHP?

How to overwrite file contents with new content in PHP? 'w' -> Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. 'w+'-> Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length.


1 Answers

Actually, my previous answer was a bit out of date. flock() blocks until the requested lock is acquired:

PHP supports a portable way of locking complete files in an advisory way (which means all accessing programs have to use the same way of locking or it will not work). By default, this function will block until the requested lock is acquired; this may be controlled (on non-Windows platforms) with the LOCK_NB option documented below.

So since file_get_contents() utilizes it, I'd assume it's the same. That said, be warned that it varies per operating system.

A bit more importantly, you don't need to lock the file in the scenario you described, for the reasons N.B. already explained. Unless you are using the CLI SAPI, I can't think of a common scenario you should be worried about file locking.

like image 52
yannis Avatar answered Sep 27 '22 23:09

yannis