How can race conditions affect the functionality of PHP scripts like the counter system?

Race conditions can occur in PHP scripts like a counter system when multiple processes try to access and update a shared resource simultaneously. This can lead to unexpected behavior such as inaccurate counts or data corruption. To prevent race conditions, you can use locking mechanisms like file locks or database transactions to ensure that only one process can access the resource at a time.

$counter_file = 'counter.txt';

// Use file locking to prevent race conditions
$fp = fopen($counter_file, 'r+');
if (flock($fp, LOCK_EX)) {
    $count = (int) fread($fp, filesize($counter_file));
    $count++;
    fseek($fp, 0);
    fwrite($fp, $count);
    flock($fp, LOCK_UN);
}
fclose($fp);

echo "Counter: $count";