Backend Development 4 min read

Using PHP flock() for File Locking: Concepts, Modes, and Example Code

This article explains PHP's flock() function for file locking, covering the purpose of file locks, basic usage syntax, lock modes (shared, exclusive, unlock), a complete example script, and important considerations to safely handle concurrent file access in backend applications.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP flock() for File Locking: Concepts, Modes, and Example Code

What Is File Locking

File locking is a mechanism that controls how multiple processes or threads access the same file, preventing data races and corruption by ensuring that only one entity can modify the file at a time.

Basic Usage of flock()

The flock() function is the primary PHP API for file locking. Its signature is:

<code>bool flock ( resource $handle , int $operation [, int &$wouldblock ] )</code>

where $handle is the file handle returned by fopen() , $operation specifies the lock operation, and the optional $wouldblock indicates whether the lock would block.

Locking Modes

flock() provides three common lock modes:

LOCK_SH (shared lock): multiple processes can read, but write operations are blocked.

LOCK_EX (exclusive lock): only one process can write; all other read/write attempts are blocked.

LOCK_UN (unlock): releases the lock.

Example Code

The following script demonstrates how to open a file, acquire a shared lock, read the file, and then release the lock:

<code>&lt;?php
$filename = "example.txt";
$handle = fopen($filename, "r");

if ($handle) {
    if (flock($handle, LOCK_SH)) { // shared lock
        // read operations here
        flock($handle, LOCK_UN); // unlock
    }
    fclose($handle);
}
?&gt;
</code>

The example shows that flock() works only on handles obtained via fopen() , the lock is visible only to the current process, and the call blocks until the lock can be acquired.

Important Notes

flock() can lock only file handles opened with fopen() .

The lock is effective only within the current process or thread; other processes cannot see it.

Lock acquisition is blocking by default; the call will wait until the lock becomes available.

Conclusion

This article detailed the PHP flock() function, including its basic usage, lock modes, a practical example, and key considerations. Mastering flock() helps developers manage concurrent file access, ensuring program stability and data integrity.

Backendconcurrencyfile-handlingfile-lockingflockphp-file
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.