Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
html
community creator

What is the SplFileObject flock() function in PHP?

Behzad Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

php
html
community creator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring