Handling file locks in PHP

By: Cory Christison  

While can do wonders if you need something to queue writing to a file while something else has access to it.

Here is my simple example:


  function write ($data, $file, $write_mode="w") {
    $lock = $file . ".lock";
     // run the write fix, to stop any clashes that may occur
     // create a new lock file after write_fix() for this writing session
    touch( $lock );
     // write to your file
    $open = fopen($file, $write_mode);
    fwrite($open, $data);
     // kill your current lock

  function write_fix ($lock_file) {
    while( file_exists($lock_file){
      // do something in here?
      // maybe sleep for a few microseconds
      // to maintain stability, if this is going to
      // take a while ?? [just a suggestion]


This method is not recommended for use with programs that will be needing a good few seconds to write to a file, as the while function will eat up alot of process cycles.  However, this method does work, and is easy to implement.  It also groups the writing functions into one easy to use function, making life easier.

Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial