Solved

What's up with my counter?

Posted on 2002-06-24
5
200 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
  • 3
5 Comments
 
LVL 7

Expert Comment

by:axis_img
Comment Utility
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 50 total points
Comment Utility
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:RQuadling
Comment Utility
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
Comment Utility
That goes without saying. :)
0
 
LVL 1

Author Comment

by:myuen
Comment Utility
Thanks.

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

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

These days socially coordinated efforts have turned into a critical requirement for enterprises.
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…
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…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

744 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now