What are common pitfalls when using PHP to write to and read from text files for counters or other purposes?

Common pitfalls when using PHP to write to and read from text files for counters or other purposes include not properly handling file permissions, not checking if the file exists before reading from it, and not properly closing the file after writing to it. To solve these issues, always set the correct file permissions before writing to or reading from a file, check if the file exists before attempting to read from it, and make sure to close the file after writing to it to release system resources.

// Writing to a text file
$filename = 'counter.txt';
$counter = 0;

if (file_exists($filename)) {
    $counter = (int) file_get_contents($filename);
}

$counter++;
file_put_contents($filename, $counter);

// Reading from a text file
$filename = 'counter.txt';

if (file_exists($filename)) {
    $counter = (int) file_get_contents($filename);
    echo "Counter: $counter";
} else {
    echo "File does not exist.";
}