Search code examples
phpfopenfwriteunlinkfile-pointer

Check if file pointer is still valid in PHP


If you do use a simple fopen/fwrite() such as:

$ref = @fopen('/path/to/file', 'x+b'); // returns false if already exists
if ($ref) {
    fwrite($ref, 'A');
    sleep(5);
    fwrite($ref, 'B');
}

How can you check that the file pointer is still valid if some other process deletes the file during the sleep?

I have considered using a simple is_file() check, but that wouldn't say if another process did the unlink() then created a new file with the same path.

For reference, fwrite seems to still return true, even though the file has been unlink()'ed.

Edit: Just to clarify, the sleep(5) is just a random time, it could be just a couple of ms, in the case of a race condition.


Solution

  • I've just made a test, and it seems that fstat is the solution:

    $fd = fopen("/path/to/file", "w");
    var_dump(fstat($fd)); // shows ['nlink'] => int(1)
    sleep(60);
    // in a shell console, remove the file
    var_dump(fstat($fd)); // shows ['nlink'] => int(0)