<?php

header('Content-type: text/html;charset=GB2312');

include("geoipcity.inc");
include("geoipregionvars.php");

function getip(){ 
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) 
$ip = getenv("HTTP_CLIENT_IP"); 
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) 
$ip = getenv("HTTP_X_FORWARDED_FOR"); 
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) 
$ip = getenv("REMOTE_ADDR"); 
else if (isset($_SERVER["REMOTE_ADDR"]) && $_SERVER["REMOTE_ADDR"] && strcasecmp($_SERVER["REMOTE_ADDR"], "unknown")) 
$ip = $_SERVER["REMOTE_ADDR"]; 
else 
$ip = "unknown"; 
return($ip); 
} 

if(empty($_GET['q'])) {
	$ip = getip();
	if($ip == "unknown") {
		echo 'alert("无法取得客户端IP");';
		die();
	}
} else {
	$pattern = "/^((1?\d?\d|(2([0-4]\d|5[0-5])))\.){3}(1?\d?\d|(2([0-4]\d|5[0-5])))$/";
	if(preg_match($pattern,$_GET['q'])) {
		$ip = $_GET['q'];
	} else {
		$ip = gethostbyname($_GET['q']);
		if(preg_match($pattern,$_GET['q'])) {
			echo 'alert("查询地址有误");';
			die();
		} 
			
	}
}

$gi = geoip_open("./GeoLiteCity.dat",GEOIP_STANDARD);
$record = GeoIP_record_by_addr($gi,$ip);
geoip_close($gi);

if($record) {
	echo 'loadInfo('.
			'"'.$_GET['q'].'",'.
			'"'.$ip.'",'.
			'"'.$record->country_code.'",'.
			'"'.$record->country_code3.'",'.
			'"'.$record->country_name.'",'.
			'"'.$GEOIP_REGION_NAME[$record->country_code][$record->region].'",'.
			'"'.$record->city.'",'.
			$record->latitude.','.$record->longitude.')';
} else {
	echo 'alert("数据库里不存在该IP的信息");';
}

 ?>