Should I use flock when reading a file in PHP?

646 views Asked by At

Ok so I am new to PHP and the example from the book shows that when I write to a file in php i should use flock($fp, LOCK_EX) after opening the file and then flock($fp, LOCK_UN) before closing the file. Like this:

$fp = fopen("$DOCUMENT_ROOT/order.txt", 'ab');
flock($fp, LOCK_EX);
fwrite($fp, $outputstring, strlent($outputstring));
flock ($fp, LOCK_UN);
fclose($fp);

But in the other example of how to read a file I am not sure if the author forgot to put flock() or it is not necessary to put flock() when reading a file. Here is the example:

$fp = fopen("$DOCUMENT_ROOT/order.txt", 'rb');
while (!feof($fp))
{
   $order = fgets($fp, 999)
   echo $order."<br/>";
}
fclose($fp);

So should I put flock() in the second example or not?

Thank you in advance.

1

There are 1 answers

0
DanielGibbs On BEST ANSWER

It is only necessary to use flock if there are going to be multiple processes accessing the file at the same time.

If the code that writes to the file is only ever going to have have one copy running at any time, then you probably don't need to use flock. However if it is possible that multiple processes could try to run the code (and therefore access the file) at the same time, then you should use flock to make sure they do it one at a time.