What is the purpose of the flock() function in PHP and how can it help prevent data corruption in text files?
The flock() function in PHP is used to manage file locking, which can prevent data corruption in text files when multiple processes try to write to the same file simultaneously. By using flock() to lock a file before writing to it, you can ensure that only one process can write to the file at a time, preventing data corruption.
$fp = fopen('file.txt', 'w');
if (flock($fp, LOCK_EX)) {
fwrite($fp, 'Data to write to file');
flock($fp, LOCK_UN);
} else {
echo 'Unable to lock file';
}
fclose($fp);