PHP visitor count

Associate
Joined
12 May 2005
Posts
1,780
hello

This is what I've come up with to count the number of IP addresses.
Is there a way to do it more efficiently ?


$cip = $_SERVER['REMOTE_ADDR'];//store IP address
$file = fopen("uviews.txt","r+"); //open uviews.txt for reading
sscanf(fgets($file),"%d",$uviews);
$string3 = fgets($file);
while(! feof($file))
{
$string3 = $string3 . fgets($file);
}
if(!(strpos($string3,$cip)))
{
$uviews++;
$string3 = $uviews . "\r\n" . $string3 . "\r\n" . $cip;
fclose($file);
$file = fopen("uviews.txt","w+"); //open uviews.txt for writing
fwrite($file,$string3);
}
fclose($file);
 
Code:
session_start();

if ( !$_SESSION['counted'] ) {
    file_put_contents('count.txt', intval(file_get_contents('count.txt')) + 1);
    $_SESSION['counted'] = 1;
}

(PHP 5 only, but PHP 5 is 100 years old so if you don't have it then sack your webhost)
 
PHP5 way:

$iprecord = text file where you store the IP addresses
$visitorip = the IP address of the person visiting your site

PHP:
$filecheck = file_get_contents($iprecord);
$pos = strpos($filecheck, $visitorip);

if $pos is false then its a new visitor, if its true the IP has been seen before.

Hope that helps.
 
It doesn't work :(.
"Cannot send session cookie - headers already sent by "
"Cannot send session cache limiter - headers already sent "

I'll stick with my fgets and sscanfs for now.

Have you added session_start() as the very first line in your php file?
 
It doesn't work :(.
"Cannot send session cookie - headers already sent by "
"Cannot send session cache limiter - headers already sent "

I'll stick with my fgets and sscanfs for now.

Put the session_start() bit at the very top of your PHP file, before any output (including whitespace). So that's anything outside your <?php ?> tags, any print/echo statements, etc.
 
The session() thing was at the start of the <PHP > block in the middle of a html file.

Yeah, it needs to come before absolutely any output.

I've found a problem with using strpos().

It returns 0 (false) if it finds a match at the start of the string, so the first line needs to be blank.

Test it like follows:

Code:
if ( $pos === false )
    // IP doesn't exist

(Also bear in mind the really edge case that a user IP of 255.255.255.25 will match an existing IP of 255.255.255.255 and thus not add a legitimate hit.)
 
Back
Top Bottom