Gath Posted October 8, 2007 Share Posted October 8, 2007 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? Quote Link to comment https://forums.phpfreaks.com/topic/72253-simple-counter-goes-puff/ Share on other sites More sharing options...
d.shankar Posted October 8, 2007 Share Posted October 8, 2007 Attach counter.txt file. Quote Link to comment https://forums.phpfreaks.com/topic/72253-simple-counter-goes-puff/#findComment-364406 Share on other sites More sharing options...
Rithiur Posted October 8, 2007 Share Posted October 8, 2007 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); } ?> Quote Link to comment https://forums.phpfreaks.com/topic/72253-simple-counter-goes-puff/#findComment-364430 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.