Reputation: 1314
This is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
class visitors
{
static $i;
function __construct()
{
$this->checkIp();
}
function createFile()
{
$fp=fopen("visit.txt","a+");
if($fp)
{
echo "<br /> File created";
return $fp;
}
else
{
echo "File creation Error Check permissions";
exit;
}
}
function fetchIp()
{
$ip=$_SERVER['REMOTE_ADDR'];
//$ip=ip2long($ip);
return $ip;
}
function writeFile()
{
$fp=$this->createFile();
$ip=$this->fetchIp();
//echo $ip;
$space="\r\n";
fwrite($fp,$ip.$space);
//self::$i++;
//echo self::$i;
}
function checkIp()
{
$fp=$this->createFile();
$ip=$this->fetchIp();
while(!feof($fp))
{
$data.=fgets($fp);
}
$uip=explode("\r\n",$data);
foreach($uip as $key)
{
if(strpos($key,$ip)!==0)
{
$this->writeFile();
}
}
}
}
$v=new visitors();
?>
</body>
</html>
I am trying to store the each visitors ip address in a text file and if the same visitor comes for the second time his ip will be written in the text file.To implement this I read the file and compare with the current ip and if they are same it doesn't call the write function.The problem is everything works but the file gets written everytime with the same ip in the newline.The comparison part fails.Please help me fix this.Leave the static i variable part.I have commented that so no problem with that.Thank you.
Note: I have read An optimized method to compare IP addresses with wildcards in PHP? and got the strpos idea from that.Before that I used ip2long and long2ip but it too resulted in the same error.I also read PHP doesn't support unsigned integers from here.Will this affect my compare operation as ip address is an unsigned 32 bit integer.
Upvotes: 0
Views: 1357
Reputation: 1794
A common way to remember ip's is to store them in a database. that way, you always have a record of their ip's and even more if you would like. =)
Best of luck
Upvotes: 1
Reputation: 39724
You don't need to loop every time, just use stristr() to see if the IP is there.
Change function
function checkIp()
{
$fp=$this->createFile();
$ip=$this->fetchIp();
while(!feof($fp))
{
$data.=fgets($fp);
}
$uip=explode("\r\n",$data);
foreach($uip as $key)
{
if(strpos($key,$ip)!==0)
{
$this->writeFile();
}
}
}
with
function checkIp()
{
$fp=$this->createFile();
$ip=$this->fetchIp();
while(!feof($fp))
{
$data.=fgets($fp);
}
if(!stristr($data, $ip)){
$this->writeFile();
}
}
Upvotes: 3