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, $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.
$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 // 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"; } ?> |
Output:
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"; } ?> |
Output:
Success Exclusive Lock and Unlock Operation
Reference: http://php.net/manual/en/splfileobject.flock.php
Recommended Posts:
- PHP | SplFileObject current( ) Function
- PHP | SplFileObject fgetc() Function
- PHP | SplFileObject eof() Function
- PHP | SplFileObject fgets() Function
- PHP | SplFileObject fgetss() Function
- PHP | SplFileObject setMaxLineLen() Function
- PHP | SplFileObject getMaxLineLen() Function
- PHP | SplFileObject fwrite() Function
- PHP | SplFileObject ftruncate() Function
- PHP | SplFileObject ftell() Function
- PHP | SplFileObject fstat() Function
- PHP | SplFileObject fread() Function
- PHP | SplFileObject fputcsv() Function
- PHP | SplFileObject seek() Function
- PHP | SplFileObject rewind() Function
- How to get the function name inside a function in PHP ?
- PHP 5 vs PHP 7
- PHP | Get PHP configuration information using phpinfo()
- PHP | php.ini File Configuration
- How to import config.php file in a PHP script ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

