How can multiple users accessing a file simultaneously affect the execution of a PHP script?

When multiple users access a file simultaneously in a PHP script, it can lead to race conditions where data integrity is compromised. To prevent this issue, you can use file locking mechanisms to ensure that only one user can write to the file at a time.

$fp = fopen("data.txt", "a+");
if (flock($fp, LOCK_EX)) {
    // Perform operations on the file
    fwrite($fp, "Data to write\n");
    flock($fp, LOCK_UN); // Release the lock
} else {
    echo "Could not lock the file!";
}
fclose($fp);