How to use flock in PHP?

php

Solution

I'm with Danack's comment - the php documentation of `flock()` contains a very good example:

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // exclusive lock will blocking wait until obtained

    fwrite($fp, "Write something here\n");

    // or ...

    execute_code_that_shouldnt_run_twice_at_the_same_time();

    flock($fp, LOCK_UN); // unlock
} else {
    echo "failed to obtain lock";
}

fclose($fp);

Note that `flock()` in default mode will blocking wait until it can obtain the lock. This is regulary the case if the other process obtains the lock currently.

But don't expect too much from the `flock()` function. It is using so called advisory locks, which can be ignored by other processes. On Linux for example PHP's `flock()` is using the kernel function `flock()`, `man 2 flock` explains how it works:

flock() places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock() and perform I/O on the file.

Meaning `flock()` will just give an advice to other processes. If they don't care about they can read or even write regardless of the lock ( or type of lock). However the man pages are about Linux other system may handle this differently. (It's not the case actually)

But, however as you are the coder of the processes you can / and should care about the lock using `flock()` every time you access the file. But you cannot be sure that another process - like a text editor - will not overwrite your file

Problem

In my php code, I want to create a reader/writer code. So there will be a file that the php code wither reads or writes to. There can only be 1 writer, or there can be many readers, but you can write and read at the same time. How can this be done in PHP? I believe you need to use the `flock` code?

Original source