The flock() function locks or releases a file.
PHP flock() Function has the following syntax.
flock(file,lock,block)
When you lock a file, we can two options.
Parameter | Is Required | Description |
---|---|---|
file | Required. | An open file to lock or release |
lock | Required. | What kind of lock to use. |
block | Optional. | Set to 1 to block other processes while locking |
Possible values for lock:
The flock() function takes a file handle as its first parameter and a lock operation as its second parameter.
PHP flock() Function returns TRUE on success or FALSE on failure.
flock() could be used like this:
<?PHP//from www . j a v a 2 s . c om
$fp = fopen( $filename,"w"); // open it for WRITING ("w")
if (flock($fp, LOCK_EX)) {
// do your file writes here
flock($fp, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print "Could not lock $filename!\n";
}
?>
Lock a file and write a string to it
<?php/*from ww w . j a v a2s. co m*/
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX)){
fwrite($file,"java2s.com");
// release lock
flock($file,LOCK_UN);
}else{
echo "Error locking file!";
}
fclose($file);
?>