PHP Function Flock
The php function flock provides a portable way of locking complete files in an advisory manner (which means that other processes may ignore it). A special bitmask LOCK_EX can be used to acquire an exclusive lock for the file. The function can also be called with LOCK_UN to release a shared lock. This method is not as fast as a semaphore, but it works on every platform and does not require any global variables. It is also more flexible than a lockfile as it is not dependent on filesystems.
The first thing to note is that the php function flock is not very good in race conditions (where multiple programs are trying to update or write to the same file). To help with this issue, I've found that adding a simple loop in which you run fopen($file, 'w') and ftruncate($file) before your flock call can help prevent the problems caused by race conditions.
Besides race conditions, the other big problem with this type of locking is that it requires your script to be able to get and then release a lock on the file. This can be a significant overhead in some cases.
In addition, the locks that flock() uses are not as strong as a standard OS-supported lock, and are prone to getting lost if your script crashes or is interrupted. If you do not want to lose your locks, you should use a system call such as fcntl() instead.