PHP | SplFileObject flock() Function
Last Updated :
20 Dec, 2018
Improve
The SplFileObject flock() function is an inbuilt function of Standard PHP Library (SPL) in PHP which is used to apply portable lock on the file.
Syntax:
php
Output:
php
Output:
bool SplFileObject::flock( $opr, $isBlock )Parameters: This function accept two parameters as mentioned above and described below: $opr: It is used to specify the operation to be apply from the following list:
- LOCK_SH: Acquire a shared lock (reader).
- LOCK_EX: Acquire an exclusive lock (writer).
- LOCK_UN: Release a lock.
- LOCK_NB: Not block while locking.
<?php
// Create Spl Object
$file = new SplFileObject("gfg.txt", "w");
// Add an Exclusive lock to gfg.txt
if ($file->flock(LOCK_SH)) {
$file->ftruncate(0);
$file->fwrite("Write GFG inside the gfg.txt");
// Release the lock
$file->flock(LOCK_UN);
echo "Success Lock and Unlock Operation";
}
else {
echo "No Lock Available";
}
?>
Success Lock and Unlock Operation.Program 2:
<?php
// Create SplFile Object
$file = new SplFileObject("gfg.txt", "w");
// Add an Exclusive lock to gfg.txt
if ($file->flock(LOCK_EX)) {
$file->ftruncate(0);
$file->fwrite("Write GFG inside the gfg.txt");
// Release the lock
$file->flock(LOCK_UN);
echo "Success Exclusive Lock and Unlock Operation";
} else {
echo "No Lock Available";
}
?>
Success Exclusive Lock and Unlock OperationReference: http://php.net/manual/en/splfileobject.flock.php