Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose PHP synchronization by the boundary you need to coordinate: a file shared by cooperating local processes, OS-level IPC shared on one machine, or tasks running through the parallel extension. These mechanisms are not interchangeable, and the PHP Manual sources cited here do not establish a general-purpose lock that works across multiple hosts.

Before choosing, identify what state is shared, which processes or tasks can access it, and whether they all run on one host. For the common case of preventing cooperating PHP scripts from entering a file-writing section together, start with flock().

How do I lock a file in PHP?

Use flock() when processes on a local system need to coordinate access to a file. It supports shared locks, which allow multiple readers, and exclusive locks, which reserve the protected section for one cooperating process. By default, acquiring a lock waits; adding LOCK_NB requests a nonblocking attempt.

A flock() lock is advisory: it does not stop a process that ignores the lock from reading or writing the file. Every participant that must be coordinated needs to use compatible locking. The PHP Manual also warns that some operating systems implement flock() at process level, which may not protect against scripts running in parallel threads of the same server instance. The documented API does not establish cross-host or network-filesystem guarantees. See the PHP Manual: flock().

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Example: exclusive lock around a write

Open the file without truncating it, acquire the lock, and only then modify its contents. Keep the stream open throughout the critical section and release the lock in cleanup code:

<?php
$path = __DIR__ . '/shared.txt';
$handle = fopen($path, 'c+'); // Create if missing; do not truncate on open.

if ($handle === false) {
    throw new RuntimeException('Could not open the file');
}

try {
    if (!flock($handle, LOCK_EX)) {
        throw new RuntimeException('Could not acquire the lock');
    }

    try {
        rewind($handle);
        $contents = stream_get_contents($handle);
        if ($contents === false) {
            throw new RuntimeException('Could not read the file');
        }

        $newContents = $contents . "updatedn";
        rewind($handle);
        if (!ftruncate($handle, 0) || fwrite($handle, $newContents) === false) {
            throw new RuntimeException('Could not write the file');
        }
        fflush($handle);
    } finally {
        flock($handle, LOCK_UN);
    }
} finally {
    fclose($handle);
}

Check both file operations and lock acquisition in production code, and adapt error handling to the application. Closing the stream releases the lock, so the handle must not be closed while the protected work is still in progress. Avoid opening the data in a truncating mode such as w before acquiring the lock: that can erase the file before coordination begins.

Blocking and nonblocking attempts

For a nonblocking exclusive attempt, use flock($handle, LOCK_EX | LOCK_NB) and handle a failed result explicitly—for example, by retrying later or returning a “busy” response. Do not treat a nonblocking failure as proof that the file is permanently unavailable.

How do I prevent two PHP scripts from writing at the same time?

If both scripts run on one machine and cooperate by taking the same exclusive flock() on the same file, only one enters the protected section at a time, subject to the operating-system and filesystem behavior described by the PHP Manual. If the shared state is not a file, or the coordination boundary is different, select an IPC or synchronization primitive suited to that boundary rather than assuming a file lock solves every concurrency problem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Shared memory does not serialize access by itself. The PHP Manual specifically warns that simultaneous access to shared memory requires synchronization. System V IPC provides semaphores, shared memory, and message queues, but its documented semaphore and inter-process messaging functionality is unavailable on Windows. Review the PHP Manual: Semaphore, Shared Memory and IPC for the APIs and platform scope.

What is the difference between a mutex and a semaphore?

A mutex permits one holder at a time; a semaphore represents a count of permits and can allow a bounded number of simultaneous users. A mutex is the natural conceptual fit when exactly one process or task should enter a critical section, while a semaphore can model a limited pool of equivalent resources. Neither definition implies fairness or starvation prevention.

The PECL sync extension provides named and unnamed OS-level synchronization objects, including mutexes and semaphores. Named objects must be created or opened with consistent names and parameters by the processes that intend to coordinate. Confirm extension installation and operating-system compatibility for the target deployment; the cited manual pages do not provide a universal installation recipe. See PHP Manual: Sync, SyncMutex, and SyncSemaphore.

Can PHP use threads?

PHP has thread-related options, but the appropriate choice depends on the runtime and deployment. For the parallel extension, the PHP Manual says that synchronization for most applications is better implemented with channels; parallelSync offers lower-level mutex and condition-variable primitives when those are specifically needed. Check that the extension and runtime fit the target environment. The manual’s guidance is in the parallelSync reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is pthreads still maintained?

No. The PHP Manual describes pthreads as “unmaintained and dead” and says it cannot be used in a web-server environment. Treat existing pthreads code as legacy and investigate migration rather than choosing it for a new web application. See the PHP Manual: pthreads.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Which PHP synchronization approach fits?

Need Starting point Key boundary or caution
Coordinate cooperating processes around a local file flock() Advisory; all participants must cooperate. Consider shared versus exclusive mode, blocking behavior, stream lifetime, and OS/filesystem behavior.
Coordinate process access to shared state on one machine using System V IPC sem_* alongside relevant shared-memory or message-queue APIs Shared memory itself is not safe against simultaneous access; the documented System V semaphore and inter-process messaging functions are unavailable on Windows.
Use named or unnamed OS-level synchronization objects PECL sync Check extension availability, consistent naming and parameters, primitive semantics, and deployment compatibility.
Coordinate tasks using the parallel extension Channels for most application cases; parallelSync for lower-level needs Choose a communication design that fits the runtime and deployment.
Maintain a codebase built on pthreads Plan a legacy migration The PHP Manual calls it unmaintained and dead and rules out use in a web-server environment.

What these locks do not establish

The PHP Manual references above describe file and OS-level synchronization; they do not establish distributed locking across hosts or guarantee behavior on a network filesystem. If PHP workers run on multiple machines, do not assume a local lock primitive is cluster-wide. Select a coordination system with documented guarantees for the actual deployment and verify those guarantees against its authoritative documentation.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.