点击计数器重置/下降非常低[重复]

This question already has an answer here:

I'm using the following basic PHP:

<?php

    if (file_exists('count_file.txt')) 
    {
        $fil = fopen('count_file.txt', r);
        $dat = fread($fil, filesize('count_file.txt')); 
        echo $dat+1;
        fclose($fil);
        $fil = fopen('count_file.txt', w);
        fwrite($fil, $dat+1);
    }

    else
    {
        $fil = fopen('count_file.txt', w);
        fwrite($fil, 1);
        echo '1';
        fclose($fil);
    }
?>

as a hit counter (I'd rather not have one but it's been insisted we do). The txt file keeps count of the hits and it works...however the counter randomly (sometimes after a few weeks, sometimes months later) decides to trip up and drops from say 4300 to 11. Can anyone tell me how to rectify this as it is becoming annoying??

</div>

You're not using any locking. If two or more requests hit your server at the same time, they're going to be stomping on each other's file operations. This sort of thing is better done in a database.

The filesize function tells you the number of bytes in the file. PHP.net can describe how the function works to you. Instead of using that function you should read a line (fgets) from the file (that line should have the hit count on it) then you add one to the hit count and then re-save.

Let me give you an analogy. You are in the kitchen and you pull a container of blueberries out and you want to know how many blueberries there are but instead you ask the container how many inches long it is. Then you get rid of all the blueberries and put the number of inches + 1 blueberries in the container. Nothing about that makes any sense but that is what your script does. If you change the line that says: $dat = fread($fil, filesize('count_file.txt')); TO $dat = fgets($fil); You should be reading how many blueberries you have, adding one to that number and re-saving.