Are there any best practices for handling file access in PHP to prevent race conditions?

Race conditions can occur when multiple processes try to access and modify the same file simultaneously, leading to unpredictable behavior or data corruption. To prevent race conditions in PHP, you can use file locking mechanisms such as `flock()` to ensure exclusive access to the file while it is being read or written.

$fp = fopen('example.txt', 'r+');
if (flock($fp, LOCK_EX)) {
    // Perform read or write operations on the file
    flock($fp, LOCK_UN); // Release the lock
} else {
    echo "Could not lock the file!";
}
fclose($fp);