Posts Tagged ‘Locking Files

Locking Files in PHP

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). If there is a possibility that more than one process could write to a file at the same time then the file should be locked.

flock() operates on fp which must be an open file pointer. operation is one of the following:

  1. To acquire a shared lock (reader), set operation to LOCK_SH
  2. To acquire an exclusive lock (writer), set operation to LOCK_EX
  3. To release a lock (shared or exclusive), set operation to LOCK_UN
  4. If you don’t want flock() to block while locking, add LOCK_NB to LOCK_SH or LOCK_EX

When obtaining a lock, the process may block. That is, if the file is already locked, it will wait until it gets the lock to continue execution. 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). flock() returns TRUE on success and FALSE on error (e.g. when a lock could not be acquired).

Here is a script that writes to a log file with the fputs function and then displays the log file’s contents:


$fp = fopen(“/tmp/log.txt”, “a”);

flock($fp, LOCK_EX); // get lock

fputs($fp, date(“h:i A l F dS, Y\n”)); // add a single line to the log file

flock($fp, LOCK_UN); // release lock


echo “<pre>”; // dump log


echo “</pre>\n”;



Tags : , , , , , , , ,