John
John

Reputation: 1009

Basic PHP hit counter loses 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;
    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);
}

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

Upvotes: 1

Views: 301

Answers (1)

GolezTrol
GolezTrol

Reputation: 116110

Length parameter must be greater than 0

Well, is it?

If filesize fails, it returns false. False is evaluated to 0.

filesize may fail if the file cannot be read at that moment. I figure that may happen if you got two simultaneous hits. One of them is writing the file while the other tries to read it. Another possibility would be that the filesize can be read, but it is 0, because another visitor had opened the file, but no written the new value yet.

So to work around this, you should apply locking to the files, do a better handling and checking of the result codes of those functions, or maybe better: move the storage to a database.

Upvotes: 1

Related Questions