unique hit counter

hey all, need some help…
I can’t get my unique hit counter to work.

The first file contains 3 functions:
[i]* Get user ip

  • Check if user ip is in ip.txt… if not then add the ip to ip.txt and increment the value of count.txt with 1.
  • Grab the number from count.txt[/i]
    [php]
<?php function ipVisitor() { if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return trim($ip); } function hit_count() { $ip_address = ipVisitor(); $ip_file = file('txt/ip.txt'); foreach($ip_file as $ip) { $ip_single = trim($ip); if($ip_address == $ip_single) { $found = true; break; } else { $found = false; break; } } if($found == false) { $filename = 'txt/count.txt'; $handle = fopen($filename, 'r'); $current = fread($handle, filesize($filename)); fclose($handle); $current_inc = $current + 1; $handle = fopen($filename, 'w'); fwrite($handle, $current_inc); fclose($handle); $handle = fopen('txt/ip.txt', 'a'); fwrite($handle, $ip_address."\n"); fclose($handle); } } function get_hits() { $filename = 'txt/count.txt'; $handle = fopen($filename, 'r'); $hits = fread($handle, filesize($filename)); fclose($handle); return $hits; } ?>[/php]

Then I have two .txt files, ip.txt and count.txt
The IPs are supposed to be stored inside ip.txt while the actual hit count will be stored inside count.txt, (the default value is set to 0).

I’m only interested in logging the IP when someone visits the index page so that’s where I call the function hit_count() which then should check if the IP is inside ip.txt. If not, well then add the IP to that file and then increment the count value with 1.

The last function, get_hits() is used on a another page.

The problem right now is that it works until the first IP has been added… after that it will add +2 to the count.txt for each new IP that visists.

Any ideas?? Help is appreciated :slight_smile:

your if($found == false) { is outside the foreach loop so will only run the once have you tried having it inside the foreach loop?

I tried that but then it doesn’t add or count IPs

Sponsor our Newsletter | Privacy Policy | Terms of Service