What are the potential issues with having multiple pages accessing the same counter file in PHP?

One potential issue with having multiple pages accessing the same counter file in PHP is the possibility of race conditions, where two or more pages try to update the counter at the same time, leading to incorrect counts or data corruption. To solve this issue, you can use file locking to ensure that only one page can access the counter file at a time, preventing race conditions.

$counter_file = 'counter.txt';

// Lock the counter file
$fp = fopen($counter_file, 'r+');
if (flock($fp, LOCK_EX)) {
    // Read the current count
    $count = intval(fread($fp, filesize($counter_file)));

    // Increment the count
    $count++;

    // Write the updated count back to the file
    fseek($fp, 0);
    fwrite($fp, $count);

    // Release the lock
    flock($fp, LOCK_UN);
} else {
    echo 'Could not lock file!';
}

// Close the file
fclose($fp);