How to detect visitor’s country using his IP address-根据IP地址转换成国家

http://de77.com/php/how-to-detect-visitors-country-using-his-ip-address

 

关键知识点:

1,IP地址转换成10进制计算公式

   1.2.3.4 = 4 + (3 * 256) + (2 * 256 * 256) + (1 * 256 * 256 * 256)

  14.155.114.41 =  41 + (114 * 256) + (155 * 256 * 256) + (14 * 256 * 256 * 256) = 245068329

   也可直接通过http://whatismyipaddress.com/ip/14.155.114.41计算

 

问题:

针对HK的固定IP能正确得出结果,而动态IP有时无法得出结果。如上面的14.155.114.41为一次实际的动态IP,它无法得出是大陆IP。

经过分析,解析不出来原因如下:

IpToCountry.csv 数据没有问题,根据245068329前三位245,查找245.php找不到记录,因为数据保存在244.php中

解决方法,修改Ip2Country.php,load函数为:

public function load($ip)
	{
		$ip = floatval($this->ip2int($ip));

		$piece = substr($ip, 0, 3);
//		echo($ip);
		$this->parseByPiece($piece, $ip);	// first parse

		if ( $this->property['countryCode'] == '' )	
		{
			$piece = floatval($piece) - 1;
			$this->parseByPiece($piece, $ip);	// second parse
		}

		if ( $this->property['countryCode'] == '' )
		{
			$this->property['countryCode'] = '?';
			$this->property['country'] = '?';
		}
		
		return $this;
	}

	private function parseByPiece($piece, $ip)
	{
		if (!file_exists($this->dir . $piece . '.php'))
		{
			$this->property['countryCode'] = '?';
			$this->property['country'] = '?';
			return $this;	
		}
		
		include $this->dir . $piece . '.php';
		
		foreach ($entries AS $e)
		{	
			$e[0] = floatval($e[0]);
			if ($e[0] <= $ip and $e[1] >= $ip)
			{
				$this->property['countryCode'] = $e[2];
				$this->property['country'] = $this->codes[$e[2]];
				return $this;
			}
		}
	}

  

 

 

posted @ 2012-07-05 10:18  Season2009  阅读(209)  评论(0编辑  收藏  举报