Hit counter losing hits every so often?

I’m using the following code:

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

    $fil = fopen('count_file.txt', w);
    fwrite($fil, 1);
    echo '1';

This works fine but every so often say every 3-4 weeks the hit counter will suddenly drop from say 1548 to 53 (just an example not the literal numbers) - anyone with ideas as to why this is happening?

the error log shows:

PHP Warning: fread() [<a href=‘function.fread’>function.fread</a>]: Length parameter must be greater than 0 in /my/home/dir/www.mysite.com/count.php on line 6

But i must admit it means little to me and i’m not sure hwo to fix it.

Perhaps it’s because two visitors are accessing the page at the same time, and causing a race condition.

Is this used on a very busy site?

wouldn’t say it is particularly busy but it has over a 1000 hits in around 2 months. Is there a modification to prevent this happening? Thanks for your reply!

Similar question (unanswered) from a few days ago:

… but might provide some other directions to look in.

unfortunately doesnt help but thanks for responding.

If you are on PHP5 I’d say use sqlite for this job - its the kind of thing it was designed to do well.

I am on PHP5 but im not really experienced enough to make adjustments to the script :frowning:

So, is this a single file which records all the page views on a small website home page?

correct, just a text file in the root dir.

We are wandering a little bit off-topic here, but given your admitted lack of programming skills - and clearly my ignorance of file locking :wink: plus your desire to know about visitors to your website - I honestly have to ask why you are not using Google Analytics. Its free and you get far more useful information about your visitors - and it will not be counting all the bots who are hitting your page – well it’ll filter out a lot of them anyway.

It’s for a friend and I have suggested GA to him but he insists he wants an on page hit counter…hence just something basic is ideal.

You have to use MySQL instead of using the text based database to solve this issue. If you have too many visitors, then it is more likely to have a condition in which two users execute the script at the same time. Which results in making the content of the text file back to zero.
Please store the data in mysql instead of using text based database.