What are the potential pitfalls of setting a reload lock for a counter in PHP?

Setting a reload lock for a counter in PHP can potentially lead to race conditions if multiple requests try to increment the counter simultaneously. To solve this issue, we can use PHP's built-in file locking mechanism to ensure only one request can access and update the counter at a time.

$counter_file = 'counter.txt';

// Acquire an exclusive lock on the counter file
$fp = fopen($counter_file, 'r+');
if (flock($fp, LOCK_EX)) {
    $counter = intval(fread($fp, filesize($counter_file)));
    
    // Increment the counter
    $counter++;
    
    // Write the updated counter back to the file
    ftruncate($fp, 0);
    fwrite($fp, $counter);
    
    // Release the lock
    flock($fp, LOCK_UN);
} else {
    echo 'Could not acquire lock on counter file';
}

// Close the file
fclose($fp);