?
Solved

What's up with my counter?

Posted on 2002-06-24
5
Medium Priority
?
207 Views
Last Modified: 2006-11-17
I'm trying to put a simple little invisible counter on my website that basically writes the hit number to a file.
For some reason, it will only increment to 1.  I think what's happening is that it always reads 0 from the file and then increments it resulting in 1.
I checked and the file (counter.txt) has full 777 permissions (which i'll fix later)

Can anyone help me out?

function updateCounter()
{
        // Check if the file exists
        if(!file_exists("counter.txt"))
                print "FILE doesn't exists";
 
        //Update counter
        $counterFile = fopen("counter.txt", 'w+');
        if($counterFile)
        {
                $chunk = fread($counterFile, 10); // Get the last counter value
                $chunk = intval($chunk);
//              print "CHUNK IS: $chunk<BR>";
                fclose($counterFile); // Close the file to rewind the pointer
                $counterFile = fopen("counter.txt", 'w+');
                if($counterFile)
                {
                        //print "CHUNK: $chunk<BR>";
                        $chunk = $chunk + 1; // Increment counter
                        fwrite($counterFile, $chunk); // Write the new value
                }
                else
                {
                        print "Did not update chunk value";
                }
//              print "Just changed the counter<BR>";
                return 0;
        }
        else
        {
//              print "failed to change the counter<BR>"; // It failed
                return -1;
        }
        fclose($counterFile); // Close the counter file
}
0
Comment
Question by:myuen
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 7

Expert Comment

by:axis_img
ID: 7106408
Hi...

Your first fopen() is the problem. Change the 'w+' to 'r+', and it should work fine.

I will post a follow-up to explain in a little more detail, as well as give a modified version of your code as an example.

Regards,
Barry
0
 
LVL 7

Accepted Solution

by:
axis_img earned 200 total points
ID: 7106418
ok...

Here is some revised code. Give it a try and let me know if you have any questions...


function updateCounter()
{
     // Open counter file
     $counterFile = fopen("counter.txt", "r+");

     // Verify open
     if($counterFile)
     {
          // Read in counter value
          $chunk = fread($counterFile, 10);
          $chunk = intval($chunk);
          print "Counter Before: $chunk<BR>";

          // Rewind file pointer
          rewind($counterFile);

          // Increment counter
          $chunk++;
          print "Counter After: $chunk<BR>";

          // Write out new counter value
          fwrite($counterFile, $chunk);
          fclose($counterFile);
          return(0);     // Success
     }
     else {
          print "Unable to open counter file...<br>";
          return(-1);     // Error
     }
}




A few notes on the changes I made.

1.) The "w+" in the fopen() was changed to "r+". When you open a file in "w+", it automatically truncates the file. The + is supposed to specify that it can also read from the file, which it can, but not in the way you think. It truncates the file _BEFORE_ allowing you to read from it. I know it may seem a bit silly, but that is the way it works. Use "r+", so that you can read from the file to get it's original contents, as well as have the ability to write to the file.

2.) I removed the use of the second fopen(), as it saves resources to only use one fopen(). Use the rewind($counterFile) or fseek($counterFile, 0) function to reset the file pointer rather than closing and opening the file again.

http://www.php.net/manual/en/function.rewind.php
http://www.php.net/manual/en/function.fseek.php

That's about it... Everything else looks ok. Hope that helps.

Barry
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 7106874
What about 2 simultaneous hits?

Using a DB is a MUCH safer option as you can get the query to retry until is suceeds in updating.

UPDATE CounterTable SET Counter = Counter + 1

Works for me.
0
 
LVL 7

Expert Comment

by:axis_img
ID: 7108201
That goes without saying. :)
0
 
LVL 1

Author Comment

by:myuen
ID: 7111587
Thanks.

I didn't know about that rewind stuff.
Later
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to implement server side field validation and display customized error messages to the client.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question