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.

Archived Comments

Most Viewed Articles (in PHP )

Installing PHP with nginx-server under windows


PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Function to convert strings to strict booleans in PHP

Convert IP address to integer and back to IP address in PHP

Function to return number of digits of an integer in PHP

Function to force strict boolean values in PHP

Function to sort array by elements and count of element in PHP

PHP pages does not display in IIS 6 with Windows 2003

Latest Articles (in PHP)

Comment on this tutorial