系统内置了get_client_ip方法用于获取客户端的IP地址,使用示例:


	$ip = get_client_ip();

上面的方法会返回一个客户端IP地址,但是如果要根据IP定位功能,则需要配合IP地址库文件(详见:http://www.kancloud.cn/manual/thinkphp/1885),网上下的IP地址库都不是很全面,因此我采用了使用第三方API获取IP定位信息的方法,这里选用的是百度API集市中的一个免费IP地址查询API(详见:http://apistore.baidu.com/apiworks/servicedetail/114.html)。

具体实现方法:


	   /**
	   *百度API集市 IP地址查询 http://apistore.baidu.com/apiworks/servicedetail/114.html
	   *@param $ip string
	   *@return string
	   **/
	   function getIpInfo($ip){
	    $ch = curl_init();
	    $url = 'http://apis.baidu.com/apistore/iplookupservice/iplookup?ip='.$ip;
	    $header = array(
	        'apikey:'.'你的apikey',
	    );
	    // 添加apikey到header
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    // 执行HTTP请求
	    curl_setopt($ch, CURLOPT_URL, $url);
	    $res = curl_exec($ch);
	    $arr = (array)json_decode($res,true);
	    if($arr['errNum']==0){
	    $ip=$arr['retData']['ip'];
	    $country=$arr['retData']['country'];
	    $provice=$arr['retData']['provice']=='None'?'':$arr['retData']['provice'];
	    $city=$arr['retData']['city']=='None'?'':$arr['retData']['city'];
	    $district=$arr['retData']['district']=='None'?'':$arr['retData']['district'];
	    $carrier=$arr['retData']['carrier']=='未知'?'':$arr['retData']['carrier'];
	    eturn($country.' '.$provice.' '.$city.' '.$district.' '.$carrier.' '.$ip);
	    }
	    else{
	    return($arr['errMsg']);
	    }

在需要ip定位的地方调用这个方法,传入通过get_client_ip方法获取的ip即可,成功则返回详细ip定位信息,失败则返回错误代码,也可以根据API说明,进一步返回更友好的错误信息。

(adsbygoogle = window.adsbygoogle || []).push({});