What is the SplFileObject flock() function in PHP?

Overview

In PHPHypertext Preprocessor, the SplFileObject flock() function is used to set a portable lock on a file, which is used to lock or unlock the file. It is a built-in feature of the Standard PHP Library (SPL).

Syntax


bool SplFileObject::flock( $operation, $isBlock)

Parameters

  • $operation: We can apply the following operations:

    • LOCK_SH: It is used to obtain a shared lock. This is a read operation.

    • LOCK_EX: It is used to obtain an exclusive lock. This is a write operation.

    • LOCK_NB: It is used to not block while the lock is on.

    • LOCK_UN: It is used to release a lock.

  • $isBlock: If the lock is block than this parameter is set to be true.

Return value

It returns true on success. Otherwise, it returns false.

Example

<?php
$file = new SplFileObject("abc.txt", "w");
if ($file->flock(LOCK_SH)) {
$file->ftruncate(0);
$file->fwrite("Characters");
$file->flock(LOCK_UN);
echo "Success Lock and Unlock Operation";
}
else if($file->isBlock)
{
echo "Blocked";
}
else
{
echo "No Lock Available";
}
?>

Explanation

  • Line 2: We create an SPL object with read and write permissions.

  • Lines 4–6: We add an exclusive lock to abc.txt.

  • Lines 8 and 9: We release the lock.

Free Resources