PHP | SplFileObject flock() Function (original) (raw)

Last Updated : 20 Dec, 2018

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:

bool SplFileObject::flock( opr,opr, 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:

$isBlock: This parameter is set to True if the lock is block.

Return values: This function returns True on on success or False on failure.

Note: Make sure the used file in below program named as gfg.txt and should have read and write permissions.

Below Programs illustrate the SplFileObject::flock() function in PHP:

Program 1:

<?php

$file = new SplFileObject( "gfg.txt" , "w" );

if ( $file -> flock (LOCK_SH)) {

`` $file ->ftruncate(0);

`` $file ->fwrite( "Write GFG inside the gfg.txt" );

`` $file -> flock (LOCK_UN);

`` echo "Success Lock and Unlock Operation" ;

}

else {

`` echo "No Lock Available" ;

}

?>

Output:

Success Lock and Unlock Operation.

Program 2:

<?php

$file = new SplFileObject( "gfg.txt" , "w" );

if ( $file -> flock (LOCK_EX)) {

`` $file ->ftruncate(0);

`` $file ->fwrite( "Write GFG inside the gfg.txt" );

`` $file -> flock (LOCK_UN);

`` echo "Success Exclusive Lock and Unlock Operation" ;

} else {

`` echo "No Lock Available" ;

}

?>

Output:

Success Exclusive Lock and Unlock Operation

Reference: http://php.net/manual/en/splfileobject.flock.php