Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Simultaneous File Writes

Tags:

I have two different PHP files that both write to the same file. Each PHP script is called by a user action of two different HTML pages. I know it will be possible for the two PHP files to be called, but will both PHP files attempt to write to the file at the same time? If yes, what will happen? Also, it is possible to make one of the PHP fail gracefully (file write will just fail, and the other PHP can write to the file) as one PHP function is less important that the other.

like image 515
Amandeep Grewal Avatar asked Jul 30 '09 22:07

Amandeep Grewal


2 Answers

The usual way of addressing this is to have both scripts use flock() for locking:

$f = fopen('some_file', 'a'); flock($f, LOCK_EX); fwrite($f, "some_line\n"); flock($f, LOCK_UN); fclose($f); 

This will cause the scripts to wait for each other to get done with the file before writing to it. If you like, the "less important" script can do:

$f = fopen('some_file', 'a'); if(flock($f, LOCK_EX | LOCK_NB)) {     fwrite($f, "some_line\n");     flock($f, LOCK_UN); } fclose($f); 

so that it will just not do anything if it finds that something is busy with the file.

like image 195
chaos Avatar answered Sep 21 '22 15:09

chaos


Please note posix states atomic access if files are opened as append. This means you can just append to the file with several threads and they lines will not get corrupted.

I did test this with a dozen threads and few hundred thousand lines. None of the lines were corrupted.

This might not work with strings over 1kB as buffersize might exceed.

This might also not work on windows which is not posix compliant.

like image 21
Antti Rytsölä Avatar answered Sep 18 '22 15:09

Antti Rytsölä