Counter resetting for some reason

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mistux
Forum Newbie
Posts: 5
Joined: Wed Oct 22, 2003 6:54 pm
Location: Indiana, USA

Counter resetting for some reason

Post by mistux »

I have several pages that all use the following counter code. The problem is that it seems to keep resetting back to zero (or some other very low number, I don't really know for sure). I have set it to several large numbers like 2 million and it works fine for a while then I go back and it shows something like 243 or whatever. It does not happen right away, sometimes it is daily, some weekly, others monthly.

Code: Select all

$fp=fopen("sheep_counter.txt","r");

//Read the previous count
$count=fgets($fp,1024);

//close the file.
fclose($fp);

$fw=fopen("sheep_counter.txt","w");

//Increment the counter
$cnew=$count+1;

//write the counter back to the log file ie., sheep_counter.txt
$countnew=fputs($fw,$count+1);

//Display VISITOR NUMBER
echo "<br> <p align=center> You are the $cnew  Visitor to This site";
fclose($fw);
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

My guess is that sometimes the opening/reading of the file fails, $count remains zero, and you write that 1 back to the file...

Here is another situatiosn where things go wrong:

visitor1 (read file) -> count = 0;
visitor2 (read file) -> count = 0;
visitor2 (write file) -> count = 1;
visitor1 (write file) -> count = 1;

Anyway, you may want to lookup some information about 'transactions'. And how they can help in concurrent requests.
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Post by neophyte »

Code: Select all

//get the counter
$count = file_get_contents("sheep_counter.txt");

//Increment the counter
$cnew=$count+1;

//Open file for writing
$fh = fopen('sheep_counter.txt', 'w');

//write the counter back to the log file ie., sheep_counter.txt
fwrite($fh,$cnew);


//Display VISITOR NUMBER
echo "<br> <p align=center> You are the $cnew  Visitor to This site";
fclose($fw);
Try something like this --- (not tested). But you should probably have some conditionals to test for a valid file handler and so forth....

Take a look at the examples here.
Post Reply