The example in this article describes the way PHP uses flock to implement file locking. Share to everyone for your reference. The specific analysis is as follows:
Flock's explanation in the official document is that flock () allows you to perform a simple read/write model that can be used on any platform (including most Unix-derived versions and even Windows). If the lock is blocked (ewouldblock error code), set the optional third argument to TRUE. The lock operation can also be fclose () free (automatically invoked when the code completes).
In simple terms, locking a file allows multiple processes to access the file in a limited way, preventing conflicts. As an example:
<?php
$file = fopen ("Test.txt", "w+");
if (Flock ($file, lock_ex))
{
fwrite ($file, "Write something");
Flock ($file, lock_un);
else
{
echo "Error locking file!";
}
Fclose ($file);
? >
Description
1. This code means to open the file Test.txt in read and write mode, when a user invokes the PHP page, the Test.txt file is operated, then the Flock ($file, LOCK_EX) code is executed, An exclusive lock on the Test.txt file, which can only be read and write by the user, is blocked if another new user wants to access the file until the former closes the file (releasing the lock).
2. If you change the code to flock ($file, LOCK_EX+LOCK_NB) to indicate a direct return of the error when locking, then if a new user accesses the file, it will output "error locking file!"
3. The syntax of the function is flock (file,lock,block), where file is required. The open file that you want to lock or release. Lock required. Specify which type of lock to use. Block Optional. Set to 1 or true to block other processes when a lock is made.
For example: Write a section of PHP code to make sure that multiple processes write to the same file at the same time successfully
function WriteData ($path, $mode, $data)
{
$fp = fopen ($path, $mode);
$retries = 0;
$max _retries = m;
do{
if ($retries > 0)
{
usleep (rand (1, 10000));
}
$retries + + 1;
} while (!flock ($FP, LOCK_EX) and $retries <= $max _retries);
if ($retries = = $max _retries)
{return
false;
}
Fwrite ($fp, "$data \ n");
Flock ($FP, lock_un);
Fclose ($FP);
return true;
}
I hope this article will help you with your PHP program design.