What are the best practices for handling file locking in PHP to prevent data corruption?

File locking in PHP is essential to prevent data corruption when multiple processes or threads are accessing the same file concurrently. To handle file locking effectively, it is recommended to use the `flock()` function with the `LOCK_EX` flag to acquire an exclusive lock on the file before writing to it. This ensures that only one process 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 be written\n");
    flock($fp, LOCK_UN); // Release the lock
} else {
    echo "Could not lock the file!";
}

fclose($fp);