Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a risk in running file_put_contents() on the same file from different PHP threads?

Tags:

php

I know file_put_contents() makes it really easy to append data to a file in PHP. I'd like to try using PHP "threads" to file_put_contents() to the same log file from different PHP threads. Is there a risk in running file_put_contents() on the same file from different PHP threads or will these threads happily block if the file is locked or being accessed by another thread?

EDIT: Found a similar question that recommends flock(), but the risk question does not seem to be fully addressed. Are these "atomic" write operations?

like image 598
buley Avatar asked Mar 29 '11 22:03

buley


2 Answers

as it says on the man page (that you gave a link for!):

// Write the contents to the file,  // using the FILE_APPEND flag to append the content to the end of the file // and the LOCK_EX flag to prevent anyone else writing to the file at the same time file_put_contents($file, $person, FILE_APPEND | LOCK_EX); 

Use the LOCK_EX flag to prevent double writes

like image 88
Naftali Avatar answered Sep 20 '22 18:09

Naftali


Simple answer, yes. clashes can occur

use something like file_put_contents($location, $data, FILE_APPEND | LOCK_EX);

When you expect multiple instances to write to the same file, you should acquire an exclusive lock so no other processes can write to the file until the current one has finished writing it's data

like image 25
Jase Avatar answered Sep 19 '22 18:09

Jase