PDA

View Full Version : [PHP] Unique hit counter



Buax
04-03-2008, 10:43 PM
This script runs off the IP address of the user, therefore if they vist the site twice, it will go up once, not twice!

To start with, we need to be able to find out their IP address.

$ip = $_SERVER[REMOTE_ADDR];

We now need a text-file to log the IP addresses. In this guide, I'll be using vists.txt - Remember to set the CHMOD to 777 otherwise the script will not be able to add in the IP addresses.

Now we need to make the script write 1 IP/line


$already="FALSE";
if(!file_exists("visits.txt"))
{
echo "Missing text file!";
}
else
{
$database=file("visits.txt");
for($i; $i<sizeof($database); $i++)
{
trim($database[$i]);
if($database[$i]!="")
$visitors++;
if($database[$i]==$ip)
$already="TRUE";
}
}


Now if $already = flase (Meaning they havn't been on the website before, we can add them to the list


if($already=="FALSE")
{
$database=fopen("visits.txt","a");
fwrite($database,"\n$ip");
fclose($database);
visitors++;


The full script for the lazy people is
</span>

</span>

</span>

<?php

$ip = $_SERVER[REMOTE_ADDR];

$already="FALSE";
if(!file_exists("visits.txt"))
{
echo "Missing text file!";
}
else
{
$database=file("visits.txt");
for($i; $i<sizeof($database); $i++)
{
$database[$i]=trim($database[$i]);
if($database[$i]!="") $visitors++;
if($database[$i]==$ip)
$already="TRUE";
}

if($already=="FALSE")
{
$database=fopen("visits.txt","a");
fwrite($database,"\n$ip");
fclose($database);
$visitors++;
}

echo "You are $visitors visitor!";

}

?>

MrCraig
05-03-2008, 12:06 PM
Now if $already = flase (Meaning they havn't been on the website before, we can add them to the list



if($already=="FALSE")
{
$database=fopen("visits.txt","a");
fwrite($database,"\n$ip");
fclose($database);
visitors++;



Havent added $ sign to visitors var in last line :)

Buax
05-03-2008, 12:12 PM
Havent added $ sign to visitors var in last line :)

Whoops! Thanks for pointing that out!

Want to hide these adverts? Register an account for free!