ok guys/gals I am new to php and web programing but I have some code I grabbed from someone else(why recreate right?) and it works. My question is once I do the following code to start the hit count how can I make it not keep counting if they refresh the page until the next visit? Second what is a good url to visit for some php coding tips and tricks?

<?php
$fp = fopen("count.txt","r");
$count = fread ($fp, filesize ("count.txt"));
fclose($fp);
$count++;
$fp = fopen("count.txt","w");
fwrite($fp, $count);
fclose($fp);
echo "$count";

    You could check the $_SERVER['HTTP_REFERER'] var and if it's the page that's just loaded (i.e they refreshed) then not log the hit) - but people can set their browsers not to send a referer line.

    Another way would be to set a cookie and not log the hit if the cookie is set.

    Of course, this way is easy to get around. You can also try logging IPs but this is also very easy to circumvent.

    There's little you can do really be sure you're not counting people multiple times, but the methods above help.

      And a reason for recreating can be gain a better understanding of the problem and it's solution - leading to the development of a better solution. Never assume the code you download is the best.

      The code you're using will give a load of nasty errors if anything goes wrong at the file level (including the first hit - where the file won't exist)

      <?php
      $counterFile='counter.log';
      file_exists($counterFile) ? $count=trim(implode('',file($counterFile))) : $count=0;
      $count++;
      
      if ($fp=@fopen($counterFile,'w'))
      {
      	fwrite($fp,$count,strlen($count));
      	fclose($fp);
      }
      else
      	echo "Couldn't write counter file";
      
      echo "$count people have visited this page.";
      ?>
      

      This code will produce a much nicer error message (i.e it won't stuff the formatting on your page) and handles non-existing files easily.

        Danny,

        Tonight is my first attempt at writing php so its nice to see someone helping out a newbie. I did this below. However I also see your posting above about cookies and $_SERVER['HTTP_REFERER'] and logging ip's. I am so new to this I dont even know where to start to create a cookie. I have been in IT for a long time on the server/networking side but after 10 years its getting old and boring (M$, Cisco, and the dead Novell). This being said I have found my new nitch, Linux and PHP. I want to learn more is there a url to a site with docs on how to learn this stuff? Second can you give an example of some of the items you listed? I have successfully setup mysql, php, apache. What a task for a newbie to get them all to talk. Ok your code below 🙂

        <center>
        <font size=4><b>Counter Added 9-10-02 You Are Visitor</b></font><br>
        <center><font color="#FF0000">
        <font size=6>

        <?php
        $counterFile='count.txt';

        file_exists($counterFile) ? $count=trim(implode('',file($counterFile))) :
        $count=0;

        $count++;

        if ($fp=@fopen($counterFile,'w'))

        {

        fwrite($fp,$count,strlen($count));
        
        fclose($fp);

        }

        else

        echo "Couldn't write counter file";

        echo "$count ";

        ?>

          Originally posted by XN85Turbo
          I want to learn more is there a url to a site with docs on how to learn this stuff?

          the php.net manual is basically a bible 🙂

          http://www.php.net/manual/en/

          or just type http://php.net/(functionname) to get a guide on it

            4 months later

            This is the counter i use is similar to the one you found i fixed it up so it does the following:
            Collects hits via user's ips (logs ips of each user)
            Generates the count based on "Unique Ips"
            The logfile only stores the ip once so if the user revisits or refreshes with the same ip it is "NOT" re-added, this is to keep file size down.
            Is fairly accurate only will show duplicate counts if someones ip changes~
            Also u can "change" the file names of the counter & the hitcounter logfile on a side note if u wanted different counters around your site.

            <?php
            /*
            Fixed up by:                                                                         
            James Moss aka: LeoXavior @ http://dfnetworks.ath.cx
            This is a simple hit counter creates/writes to file:::> counter.hits
            Set Vars uptop to the file you want to make and your start date.
            -Updated: fixed the repeat logged ips so the file doesn't get bloated
            */ /* Core Variables */ $filename = "counter.hits" ; $startdate = "December 2002" ; $ip = getenv("REMOTE_ADDR") ; $currentip = "$ip"; $file = file($filename); $file = array_unique($file); /* This is the guts of the counter first parts checks if ip already exists */
            $file = "$filename"; $fd = fopen ($file, "r"); $fget= fread ($fd, filesize ($file)); fclose ($fd); $totalips = htmlspecialchars($fget); /* does the ip exist? if yes don't re-add it checks using the pre_match */ if (preg_match ("/$ip/i", "$totalips")) {$file = file($filename); $file = array_unique($file); $hits = count($file); echo "Visitors since,<br>"; echo "$startdate: 000$hits";}
            /* If the ip didn't exist then add it */ else { $fd = fopen ($filename , "r"); $fstring = fread ($fd , filesize ($filename)) ; fclose($fd) ; $fd = fopen ($filename , "w"); $fcounted = $fstring.$currentip."\n"; $fout= fwrite ($fd , $fcounted); fclose($fd); $file = file($filename); $file = array_unique($file); $hits = count($file); echo "Visitors since,<br>"; echo "$startdate: 000$hits"; } ?>

              That is great news. So the new question is does the couter let the user add a hit once they close their browser and reopen or revisit the site at a later time?

                This one does not no only time it will repeat a count is is a visitor's ip changes.
                example:
                ~dialup users usually have a new ip everytime they login to their isp, and some dsl users if they reboot there router, cable is alway's static tho (generally)

                this could be altered tho so if an ip is "similar" to another ip it wont re-add it as a new hit..
                say your ip was logged :
                123.456.789

                then your ip changed to
                123.456.111

                could rework it so anything starting with the first 7 characters of an ip ditching the last part ==> .789 or .111 but that would take a lil work.

                  I can work on this some if you need it may take 10-20 minutes to work it out, but could store a cookie basically say "hey i've been here don't re-add me!", other wise log there ip which will = logging a new hit ...... etc..

                  That could work to be more accurate if u need it to be, generally tho 60% of the will have basically a static ip (wont change often)

                  Another ~?~
                  What are you wanting this counter to do?
                  A page hit counter? (only show unique visit counts)

                  Lil Fun thing u may like btw:
                  To show how long it takes a page to load example:
                  www.dfnetworks.ath.cx

                  include this at the top of your page:

                  <? 
                  $time = explode(" ", microtime());
                  $stime = $time[1] . substr($time[0],1,strlen($time[0]));
                  ?>
                  

                  Include this where you want to show the generation time:

                  <?
                  $time2 = explode(" ", microtime());
                  $etime = $time2[1] . substr($time2[0], 1, strlen($time2[0]));
                  echo "\nGenerated in:<br />" . substr($etime - $stime,-0,8) . " seconds\n";
                  ?>
                  

                  Will produce something roughly like:
                  Generated in:
                  1.076629 seconds

                    I might be more intrested in one that resets when the session does. I haven't had much time to try it in the last few months.

                    Robert

                      Now your thinking!
                      I like that

                      basically you need an if(!isset(session_value)){do the hit counter code here}

                      session_value being something like:
                      session_count maybe
                      and register it etc..
                      that would work very easilly within your current session setup probably just add an if statement similar to above to include the counter scripst etc.. would work beautiflly probably

                      *Note: would take a lil work but should work great

                      if u need more help on this let me know how to reach u via aim/msn/icq if you'd like @mail me at darkside_net@hotmail.com
                      or on my site @ www.dfnetworks.ath.cx just post in the forum say sups somewhere.

                        I will play with it later. I have to go over to the in-laws for the afternoon. I think we are on to something that can benefit a lot of forum members who want a more accurate count. I will post the results once I play with it some. Thanks for your help I am sure the forum will agree or atleast the newbies running websites.

                        😃

                          Anytime, im actually gonna play with the session idea some also ill try post back sometime in this thread or the general help thread soon also if not here look in general help for a new hit counter posting....

                            a month later

                            I use a session based counter to log total uniques and a hit counter to log raw hits, incorporating an IP tracking system into it as well and then I will release it upon the world.

                            Sessions are better than IP's for unique tracking in my opinion because the user has to close all explorer windows to close the current session

                              corporateboy,

                              Sure would be nice to see some of that code you wrote.

                                a year later

                                Fixed up Counter:
                                This is the counter i use is similar to the one you found i fixed it up so it does the following:
                                Collects hits via user's ips (logs ips of each user)
                                Generates the count based on "Unique Ips"
                                The logfile only stores the ip once so if the user revisits or refreshes with the same ip it is "NOT" re-added, this is to keep file size down.
                                Is fairly accurate only will show duplicate counts if someones ip changes~
                                Also u can "change" the file names of the counter & the hitcounter logfile on a side note if u wanted different counters around your site.

                                PHP:

                                <?php
                                /
                                Fixed up by:

                                James Moss aka: LeoXavior @ http://dfnetworks.ath.cx

                                This is a simple hit counter creates/writes to file:::> counter.hits

                                Set Vars uptop to the file you want to make and your start date.

                                -Updated: fixed the repeat logged ips so the file doesn't get bloated

                                /
                                /
                                Core Variables
                                /
                                $filename = "counter.hits" ;
                                $startdate = "December 2002" ;
                                $ip = getenv("REMOTE_ADDR") ;
                                $currentip = "$ip";

                                $file = file($filename);
                                $file = array_unique($file);

                                /
                                This is the guts of the counter
                                first parts checks if ip already exists
                                /

                                $file = "$filename";

                                $fd = fopen ($file, "r");

                                $fget= fread ($fd, filesize ($file));

                                fclose ($fd);

                                $totalips = htmlspecialchars($fget);

                                /
                                does the ip exist?
                                if yes don't re-add it
                                checks using the pre_match
                                /
                                if (preg_match ("/$ip/i", "$totalips"))

                                {$file = file($filename);
                                $file = array_unique($file);
                                $hits = count($file);
                                echo "Visitors since,<br>";
                                echo "$startdate: 000$hits";}

                                /
                                If the ip didn't exist
                                then add it
                                /

                                else
                                {

                                $fd = fopen ($filename , "r");
                                $fstring = fread ($fd , filesize ($filename)) ;
                                fclose($fd) ;
                                $fd = fopen ($filename , "w");
                                $fcounted = $fstring.$currentip."\n";
                                $fout= fwrite ($fd , $fcounted);
                                fclose($fd);
                                $file = file($filename);
                                $file = array_unique($file);
                                $hits = count($file);
                                echo "Visitors since,<br>";
                                echo "$startdate: 000$hits";
                                }

                                ?>

                                How exactly does this code re-count visitors? it sounds to me that its counting one hit per ip and then never again on that particular ip...

                                I tried it and after some time again but it didnt count... Not very accurate after all? 😕 or am i doing something wrong 🙂

                                  Write a Reply...