How can race conditions be avoided when multiple users are accessing the same file in PHP?

Race conditions can be avoided when multiple users are accessing the same file in PHP by using file locking mechanisms. By implementing file locking, you can ensure that only one user can write to the file at a time, preventing conflicts and data corruption.

$fp = fopen("file.txt", "a+");

if (flock($fp, LOCK_EX)) {
    // Perform file operations here
    fwrite($fp, "Data to write\n");
    flock($fp, LOCK_UN); // Release the lock
} else {
    echo "Could not lock the file!";
}

fclose($fp);