tags:

views:

286

answers:

4

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.

+4  A: 

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");
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");
fclose($f);

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

chaos
Exactly what I was looking for! That was so easy, I should have checked the PHP documentation more.
AmandeepGrewal
Take care using flock() since the function isn't atomic.
arul
+1  A: 

Take a look at the flock function.

cdmckay
A: 

FYI: flock only works on *nix and is not available on Windows

xentek
From the PHP documentation: "flock() allows you to perform a simple reader/writer model which can be used on virtually every platform (including most Unix derivatives and even Windows)."
cdmckay
A: 

Please note:

As of PHP 5.3.2, the automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.

The updated backward compatible code is:

if (($fp = fopen('locked_file', 'ab')) !== FALSE) {
    if (flock($fp, LOCK_EX) === TRUE) {
        fwrite($fp, "Write something here\n");
        flock($fp, LOCK_UN);
    }

    fclose($fp);
}

i.e. you have to call flock(.., LOCK_UN) explicitly because fclose() does not do it anymore.

Marcello Nuccio