Jump to content

Simple counter goes 'puff'


Gath

Recommended Posts

Hi.

 

I placed a simple counter in some of my pages. It works like it should... except, every now and then it... resets. And i cant figure out why. I dont know to what exact number it resets, sicne i dont know when it actually happens. First time i noticed it the counter should be at around 5000, but was at around 300. Second time, was over 1000, but it became at 200. And those are the ones i noticed, maybe some pages 'resetted' more often. Dunno.

 

Code is placed in the very end of hte file, none variable is used before.

 

<?php
$fp = fopen("counter.txt", "r");
$count = fread($fp, 8000);
fclose($fp);
$count = $count + 1;
$fp = fopen("counter.txt", "w");
fwrite($fp, $count);
fclose($fp);
?>

 

Any ideas?

Link to comment
https://forums.phpfreaks.com/topic/72253-simple-counter-goes-puff/
Share on other sites

Well, basically what you have here is a race condition. The reason why your counter resets, is because you have two processes accessing the same file simultaneously, causing it to "corrupt" the data, which in practice resets the counter.

 

In order to avoid this, you need to use file locking mechanism, which will prevent two processes from accessing the file at the same time. For example, you coul do it like this:

 

<?php
$fp = fopen("counter.txt", "r+");

if (flock($fp, LOCK_EX))
{
$count = intval(fread($fp, filesize("counter.txt")));
$count = $count + 1;

ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, $count);
fclose($fp);
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.