Example
Lock and release a file:
html
<?php
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX)) {
fwrite($file,"Add some text to the file.");
fflush($file);
// release lock
flock($file,LOCK_UN);
}
else {
echo "Error locking file!";
}
fclose($file);
?>
Definition and Usage
The flock() function locks and releases a file.
Syntax
text
flock(file, lock, block)
Parameter Values
| Parameter | Description |
|---|---|
| file | Required. Specifies an open file to lock or release |
| lock | Required. Specifies what kind of lock to use. Possible values: LOCK_SH - A shared lock (reader). Allow other processes to access the file LOCK_EX - An exclusive lock (writer). Prevent other processes from accessing the file LOCK_UN - Release the lock LOCK_NB - Avoid blocking other processes while locking |
| block | Optional. Set to 1 to block other processes while locking |
Technical Details
| Return Value: | TRUE on success, FALSE on failure |
|---|---|
| PHP Version: | 4.0+ |