Posts

Check if a file is open by another process in PHP (Linux/UNIX)

The PHP flock() function is good when the file locking method is used the same way by all programs that will lock the file.

However, you can’t check if any process in the system is actually using the file or not. If you for example are monitoring an incoming ftp folder, you don’t want to start processing a file until the file is completely tranferred (i.e. wait until the ftp daemon is no longer having the file open).

The following code illustrates how the command lsof can be used for the purpose: 

<?php
$filename = "locktest.txt";
$directory = ".";
while (1) {
        $result = exec("lsof +D $directory | grep -c -i $filename");
        if ($result == "0") {
                echo "$directory/$filename is NOT open ($result)\n";
        } else {
                echo "$directory/$filename IS OPEN ($result)\n";
        }
        sleep(1);
};
?>