How can multiple users accessing a counter script simultaneously affect its functionality in PHP?

When multiple users access a counter script simultaneously in PHP, it can lead to race conditions where the counter value is not accurately incremented. To solve this issue, you can use file locking to ensure that only one user can access and update the counter at a time.

$counterFile = 'counter.txt';

// Lock the file before reading or writing
$fp = fopen($counterFile, 'r+');
if (flock($fp, LOCK_EX)) {
    $counter = (int)fread($fp, filesize($counterFile));
    $counter++;

    fseek($fp, 0);
    fwrite($fp, $counter);
    flock($fp, LOCK_UN);
}
fclose($fp);

echo "Counter: " . $counter;