续前两篇通过手机号码获取用户归属地后
为确保程序稳定高效运行,在此增加通过客户端ip获取用户所在地
(通过手机号码,只能获取用户手机号注册城市,如程序关于地点有明确要求,请删减使用)
/**
* 手机号获取城市
* 2018-06-21 Angus
* zhn6@sina.cn
* */
public function PhoneCity($Mobile){
$City = array();
$Url = 'http://mobsec-dianhua.baidu.com/dianhua_api/open/location?tel='.$Mobile;
$result = json_decode($this ->getCurlRequest($Url), true);
if(isset($result['response'][$Mobile]['detail']['area'][0]['city'])){
$City['cityname'] = $result['response'][$Mobile]['detail']['area'][0]['city'];
$City['province'] = $result['response'][$Mobile]['detail']['province'];
}else{
$Url = 'https://www.so.com/s?q='.$Mobile.'&src=hao_tool';
$result = $this ->postCurlRequest($Url);
preg_match('/<p class=\"mh-detail\">([^<]*)<\/p>/is',$result, $re);
$qian=array(" ","\t","\r","\n");
$hou=array("","","","|");
$str = str_replace($qian,$hou,$re[1]);
$CityArray = explode('|', $str);
$City['cityname'] = empty($CityArray[4])?$CityArray[3]:$CityArray[4];
$City['province'] = $CityArray[3];
}
$City['cityid'] = M('Area') ->where(array('name'=>array('like', $City['cityname']."%"), 'level'=>2)) ->getField('zone_id');
return $City;
}
/**
* Ip获取城市
* */
public function IpCity(){
$ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".get_client_ip());
$ip = json_decode($ip,true);
if($ip['code'] != 0){return false;}
if($ip['data']['city_id'] == 'xx' || $ip['data']['region'] == 'XX' || $ip['data']['city_id'] == 'local'){return false;}
return array('cityname'=>$ip['data']['city'], 'cityid'=>$ip['data']['city_id'], 'province'=>$ip['data']['region']);
}
function getCurlRequest($Url){
$ch = curl_init(); //初始化CURL句柄
curl_setopt($ch, CURLOPT_URL, $Url); //设置请求的URL
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而s不是直接输出
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); //设置请求方式
curl_setopt($ch,CURLOPT_HTTPHEADER,array("X-HTTP-Method-Override: GET"));//设置HTTP头信息
$document = curl_exec($ch);//执行预定义的CURL
curl_close($ch);
return $document;
}
function postCurlRequest($Url){
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $Url );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ( $ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
'Content-Type: application/json'
));
$result = curl_exec ( $ch );
curl_close ( $ch );
return $result;
}