I'd just like to make a few comments here. These are my own opinions, and not necessarely correct. You have been warned...
First of all, you always want to use flock. Getting sharing violations in your code is sloppy coding (unless you for some reason want to).
Never keep a file open longer than you have to. Doing
or other unnecessary stuff while having a file opened is bad coding.
Using LOCK_EX means you have an *exlusive* lock. That means that no other applications can access the file at this time. This is the typical thing to do when doing transactions. (Which is doing several operations, and you don't want others to read the data while you're in the middle of this process, as this will give them inconsistent/wrong data).
Using LOCK_SH means that you have full access to the file, but other applications can still *read* from it. Without waiting for you to release the lock! Not good for transactions, obviously. But using it for reading a web-page counter is a perfect task.
Also, if you don't want to wait for a file to become unlocked, you can also use LOCK_NB. If the file is locked, this will return imidiately with another return status.
See
for a complete description.
Hope this helps,
Palooka