PHP Filesystem flock() Function
The PHP Filesystem flock() function is used to lock or release a file. This function allows us to perform a simple reader/writer model that can be used virtually on every platform.
The possible locks are LOCK_SH: Shared lock (reader). Allow other processes to access the file, LOCK_EX: Exclusive lock.Prevent other processes from accessing file, LOCK_UN: Release a shared or exclusive lock, and LOCK_NB: Avoids blocking other processes while locking.
These locks are used only in the current PHP process, and if the permission allows, other processes can modify or delete the PHP-locked file. This function is mandatory under Windows.We can use the fclose() function to release the lock operation, which can be automatically called when the script execution is completed.
This is a brief explanation of how it works −
- Open a File: To lock a file, you must first open it with fopen().
- Lock the File: Use flock() to lock the file. This ensures that no other script will be able to access it until you are done.
- Read or write in the file: execute the file actions (read or write).
- Open the File: To open the file once more when you are done, use flock().
- Close the Document: To close the file, use fclose().
Syntax
Below is the syntax of the PHP Filesystem flock() function −
bool flock ( resource $handle , int $operation [, int &$wouldblock ] )
Parameters
Here are the required and optional parameters of the flock() function −
| Sr.No | Parameter & Description |
|---|---|
| 1 |
handle(Required) It is the file pointer resource. |
| 2 |
operation(Required) The type of lock. It can be − |
| 3 |
wouldblock(Required) The third argument is optional and is set to 1 if the lock blocks. |
Return Value
It returns TRUE on success, or FALSE on failure.
PHP Version
The flock() function was first introduced as part of core PHP 4 and work well with the PHP 5, PHP 7, PHP 8.
Example
So first we will see the basic usage of the PHP Filesystem flock() function to make an exclusive lock on the given file. Here is the simple demonstration of this example −
<?php
$file = fopen("/PhpProject/sample.txt", "w+");
// exclusive lock
if(flock($file, LOCK_EX)) {
fwrite($file, "flock function");
// release lock
flock($file, LOCK_UN);
echo $file;
} else {
echo "Error locking file!";
}
fclose($file);
?>
Output
When you run this script, you will see something like the below result −
Resource id #12345
Example
So now we will see how we can write the content and read the written content after using the flock() function.
<?php
$file = fopen("/PhpProject/sample.txt", "w+"); // Open the file for reading and writing
// exclusive lock
if(flock($file, LOCK_EX)) {
fwrite($file, "flock function");
// release lock
flock($file, LOCK_UN);
} else {
echo "Error locking file!";
}
fclose($file); // Close the file
// Reopen the file to read its content
$file = fopen("/PhpProject/sample.txt", "r");
$content = fread($file, filesize("/PhpProject/sample.txt"));
fclose($file);
echo $content; // Outputs the content of the file
?>
Output
This will produce the following result −
flock function
Example
Let's assume we have a script that logs messages to a file. So with the help of flock() function we can ensure that at a time only one process can write to the file.
In our code, the flock($file, LOCK_EX) will try to get an exclusive lock and the flock($file, LOCK_UN) will release the lock after writing process is done.
<?php
$logFile = "/PhpProject/log.txt";
$message = "This is a log message.\n";
// Open the log file in append mode
$file = fopen($logFile, "a+");
// Try to get an exclusive lock for writing
if (flock($file, LOCK_EX)) {
// Write the message to the log file
fwrite($file, $message);
// Release the lock
flock($file, LOCK_UN);
echo "Message logged successfully.";
} else {
echo "Error locking file!";
}
fclose($file); // Close the file
?>
Output
If the lock is successful and the message is written, the output will be −
Message logged successfully.
If there is an error in locking the file, the output will be −
Error locking file!
Note
If flock() is unable to lock the file, it will return false so you can handle this in your code to stop undesirable behavior.
Summary
The flock() function in PHP is used to control file locking. By using file locking to stop multiple scripts from accessing the same file at a time. So using this we can prevent data corruption.