What are common pitfalls when using PHP for counting visitors on a website?

One common pitfall when using PHP for counting visitors on a website is not properly handling concurrent requests, which can lead to inaccurate visitor counts. To solve this issue, you can use file locking to ensure that only one request can update the visitor count at a time.

$lockFile = 'visitor_count.lock';
$visitorCountFile = 'visitor_count.txt';

$lockHandle = fopen($lockFile, 'w');
if (flock($lockHandle, LOCK_EX)) {
    $visitorCount = (int)file_get_contents($visitorCountFile);
    $visitorCount++;
    file_put_contents($visitorCountFile, $visitorCount);
    flock($lockHandle, LOCK_UN);
} else {
    // Handle lock failure
}
fclose($lockHandle);