What are race conditions in PHP and how can they be avoided?

Race conditions in PHP occur when multiple processes or threads try to access and manipulate shared data concurrently, leading to unexpected results. To avoid race conditions, you can use locking mechanisms like mutex or semaphores to ensure that only one process can access the shared data at a time.

$lock = fopen("lockfile.lock", "w");

if (flock($lock, LOCK_EX)) {
    // Critical section - access and manipulate shared data here
    flock($lock, LOCK_UN); // Release the lock
} else {
    // Handle the case where the lock couldn't be acquired
}

fclose($lock);