What are some potential pitfalls of using a text-based counter system in PHP?

One potential pitfall of using a text-based counter system in PHP is the risk of data corruption or loss if multiple users try to access and update the counter simultaneously. To solve this issue, you can implement a file locking mechanism to ensure that only one user can access and update the counter at a time, preventing data corruption.

$counterFile = 'counter.txt';

// Acquire an exclusive lock on the counter file
$fp = fopen($counterFile, 'r+');
if (flock($fp, LOCK_EX)) {
    // Read the current counter value
    $counter = intval(fread($fp, filesize($counterFile)));

    // Increment the counter value
    $counter++;

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

    // Release the lock and close the file
    flock($fp, LOCK_UN);
    fclose($fp);

    echo "Counter value: " . $counter;
} else {
    echo "Could not acquire lock on counter file.";
}