How can race conditions be prevented in PHP when multiple instances are accessing the same file?

Race conditions in PHP when multiple instances are accessing the same file can be prevented by using file locking mechanisms. By using file locking, we can ensure that only one instance can access the file at a time, preventing conflicts and data corruption.

$fp = fopen("data.txt", "r+");

if (flock($fp, LOCK_EX)) {
    // Perform operations on the file
    fwrite($fp, "Data to be written");
    
    flock($fp, LOCK_UN); // Release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);