Check Whether a PHP Stream Supports File Locking

Last updated: December 5, 2026.

Use stream_supports_lock() to check whether a stream supports PHP’s file locking interface. Then call flock() and check its result before changing the protected data.

<?php

// All cooperating processes open the same application-owned lock file.
$lock = fopen(__DIR__ . '/report.lock', 'c+b');
if ($lock === false) {
    throw new RuntimeException('Cannot open the lock file');
}

try {
    if (!stream_supports_lock($lock)) {
        throw new RuntimeException('This stream cannot be locked');
    }

    if (!flock($lock, LOCK_EX | LOCK_NB, $wouldBlock)) {
        throw new RuntimeException($wouldBlock ? 'Report is busy' : 'Lock failed');
    }

    // Update the protected report here while the handle remains open.
} finally {
    fclose($lock);
}

Distinguish unsupported locking from a busy lock

The capability check answers whether the stream supports the interface. It does not inspect whether someone else holds the lock. With a nonblocking acquisition, the third flock() argument is set when the operation would have blocked. Use that case for a busy response or a bounded retry, and treat other acquisition failures as operational errors.

The example uses a local lock file and a mode that does not truncate it. Keep the same lock file for all participants. In particular, do not delete or replace it while another worker may have it open. Closing the handle releases an acquired lock.

Verify the coordination your application depends on

A lock only coordinates participants that use compatible locking. For a deployment spanning multiple hosts, verify the real storage and filesystem behavior before relying on PHP file locking. A custom stream wrapper can implement its own locking behavior, so the acquisition result remains relevant even when the capability check reports support.

Test contention with two processes opening the same file, then confirm acquisition works again after the first process closes its handle. A temporary memory stream is a separate check for an unsupported stream.

Documentation

Related guides

Sergey Kornilov

Sergey Kornilov