Locking files
In PHP, if you are writing to a file, you can use the flock() function. The first argument is the file pointer (I use $fp = fopen()) and the second argument can be one of
LOCK_SHto acquire a shared lock (reader).LOCK_EXto acquire an exclusive lock (writer).LOCK_UNto release a lock (shared or exclusive).LOCK_NBif you don't wantflock()to block while locking. (not supported on Windows)
If you use LOCK_EX that means only the process that ran flock() can write to the file. That doesn't mean that all processes can't write to the file. It's a lock within the web environment. If you were on, say a UNIX system and you ran flock() but a cron job wants to write to it, it can!!! flock() is contained within PHP. (Read this, but don't quote my explanation 100%). Read the php flock function documentation » for more information.
An example would be
if(flock($fp,LOCK_EX)){
#> do some stuff
}
fclose($fp);
[Click to add or edit comments])
Please prepend comments below including a date