Locking Files with flock()

The fopen() function, when called on a file, does not stop that same file from being opened by another script. This means you might find one script reading from a file as another is writing or worse, two scripts writing to the same file simultaneously.

The solution to this problem is to use file locking , which is implemented in PHP using the flock() function. When you lock a file, you have the option of marking it a read-only lock, thereby sharing access to the file with other processes, or an exclusive lock, allowing you to make changes to the file. On Unix, flock() is advisory, meaning that the OS is free to ignore it. Windows forces the use of flock(), whether or not you ask for it.

The flock() function takes a file handle as its first parameter and a lock operation as its second parameter. File handles you know already, and the operations are simple: LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a lock. Calling flock() will return true if the file lock was retrieved successfully, or false if it failed. So, for example, flock() could be used like this:

    $fp = fopen( $filename,"w"); // open it for WRITING ("w")
    if (flock($fp, LOCK_EX)) {
            // do your file writes here
            flock($fp, LOCK_UN); // unlock the file
    } else {
            // flock() returned false, no lock obtained
            print "Could not lock $filename!\n";
    }

File locking requires a fairly modern file system, which does not include the original version of Microsoft's FAT file ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.