What are the potential pitfalls of using file_put_contents() without proper locking mechanisms in PHP?

When using file_put_contents() without proper locking mechanisms in PHP, there is a risk of data corruption or loss if multiple processes try to write to the same file simultaneously. To prevent this issue, you can use file locking mechanisms such as flock() to ensure exclusive access to the file during writing.

$file = 'example.txt';
$data = 'Hello, World!';

$fp = fopen($file, 'a');
if (flock($fp, LOCK_EX)) {
    file_put_contents($file, $data, FILE_APPEND);
    flock($fp, LOCK_UN);
} else {
    echo "Could not lock file!";
}
fclose($fp);