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
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);
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.