What is the purpose of using the flock command in PHP when writing to a text file?

The purpose of using the flock command in PHP when writing to a text file is to prevent multiple processes or threads from accessing and modifying the file simultaneously. This helps to avoid data corruption and ensure that the file is written to correctly.

$fp = fopen("example.txt", "a");
if (flock($fp, LOCK_EX)) {
    fwrite($fp, "Hello, World!\n");
    flock($fp, LOCK_UN);
} else {
    echo "Couldn't lock the file!";
}
fclose($fp);