How does flock prevent collisions when multiple users access the same script writing to a text file?
When multiple users access the same script writing to a text file, collisions can occur if they try to write to the file simultaneously. To prevent collisions, you can use the flock function in PHP to lock the file before writing to it and unlock it after the write operation is complete. This ensures that only one user can write to the file at a time, preventing data corruption.
$fp = fopen('data.txt', 'a+');
if (flock($fp, LOCK_EX)) {
fwrite($fp, "Data to write to the file\n");
flock($fp, LOCK_UN);
} else {
echo "Could not lock the file!";
}
fclose($fp);