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_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB if you don't want flock() 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

$fp = fopen('myfile.txt','w');

if(flock($fp,LOCK_EX)){
  #> do some stuff
}

fclose($fp);

http://www.php.net/flock »

Page Comments (Click to edit)






[Click to add or edit comments])

Please prepend comments below including a date

Design by N.Design Studio, adapted by solidGone.org (version 1.0.0)
Have a nice day.