« I Posted My First php Program | Main | Added a Hit Counter to This Blog »

Saturday, August 01, 2009

Fixing the Hit Counter

I added some code to the hit counter that I posted in my previous entry. In this case, I really did write the code that I added. The new code checks the IP address of the computer accessing the site, and if it is the same IP as last time, the hit counter is not incremented. So now it is not possible to just sit on the site and bump up the counter.

The code stores the IP in a file called "visitor.txt" and checks it at the next visit to see if it is the same computer. I have seen php hit counters that keep all of the IP's in a file and never bumps the counter if that IP ever goes to the site ever again, but that is not what I wanted to do. So I wrote my own. I guess I am now a php programmer.

This has been an exercise in learning php coding so that I can write other functions for this blog such as a search function (Google has not found me yet, so it isn't doing it for me). Here is the code for the hit counter. Go ahead and use it if you want to.

<?php
  $file = 'counter.txt';
  $visitor_file = 'visitor.txt';

  // Create the counter file if not there
  if(!file_exists($file))
  {
      $handle = fopen($file, 'w');
      fwrite($handle, 0);
      fclose($handle);
  }

  // Create the visitor file if not there
  if(!file_exists($visitor_file))
  {
      $vhandle = fopen($visitor_file, 'w');
      fwrite($vhandle, 0);
      fclose($vhandle);
  }

  // Get the previous visitor from the file
  $last_visitor = file_get_contents($visitor_file);
  // Get the current visitor from the server
  $current_visitor = $_SERVER["REMOTE_ADDR"];
  // Update the counter only if the two are different
  if(!($last_visitor == $current_visitor))
  {
    
    $count = file_get_contents($file);
    // Trim the newline if one is there. A newline 
    // messes up the arithmetic operation on the string
    $count = trim($count);
    $count++;

    // Update the counter value in the file
    if(is_writable($file))
    {
      $handle = fopen($file, 'w+');
      fwrite($handle, $count);
      fclose($handle);
    }
    else
    {
        echo 'Could not increment the counter!<br />';
    }

    // Update the visitor file with current visitor
    if(is_writable($visitor_file))
    {
      $vhandle = fopen($visitor_file, 'w+');
      fwrite($vhandle, $current_visitor);
      fclose($vhandle);
    }
    else
    {
        echo 'Could not save current visitor!<br />';
    }
  }
  else
  {
    // Report what is in the count file without changing it.
    $count = file_get_contents($file);
    // Trim the newline if one is there. A newline 
    // messes up the arithmetic operation on the string
    $count = trim($count);
  }

  echo number_format($count);
?>   
Posted by Brian S. Kimerer at 11:14 PM

This site and all of its contents are copyright Brian S. Kimerer 2009