//获取用户真实IP地址直接调用该方法
function getIP()
{
static $realip;
if (isset($_SERVER)){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$realip= $_SERVER["HTTP_X_FORWARDED_FOR"];
}else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
$realip= $_SERVER["HTTP_CLIENT_IP"];
}else {
$realip= $_SERVER["REMOTE_ADDR"];
}
}else {
if (getenv("HTTP_X_FORWARDED_FOR")){
$realip= getenv("HTTP_X_FORWARDED_FOR");
}else if (getenv("HTTP_CLIENT_IP")) {
$realip= getenv("HTTP_CLIENT_IP");
}else {
$realip= getenv("REMOTE_ADDR");
}
}
return $realip;
}
/**
* 根据 IP 获取 地理位置
* 淘宝IP接口 //有次数限制,容易出现错误
* @Return: array
*/
function getCity1()
{
$ip = '180.149.130.16';
$url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
$ipArr=json_decode($this->curl_get($url),true);
if((string)$ipArr['code']=='1'){
return false;
}
print_r($ipArr) ;
}
//调用后返回值经常是这个,不太好用
{
"msg": "the request over max qps for user ,the accessKey=public",
"code": 4
}
function getCity(){
$ip = '180.149.130.16';
$url="https://apis.map.qq.com/ws/location/v1/ip?ip=".$ip."&key=key";//key需要申请https://lbs.qq.com/service/webService/webServiceGuide/webServiceIp
$ipArr=json_decode($this->curl_get($url),true);
if(empty($ipArr)){
$this->getCity($ip);
} print_r($ipArr) ;
}
//下面是返回值
Array
(
[status] => 0
[message] => query ok
[result] => Array
(
[ip] => 180.149.130.16
[location] => Array
(
[lat] => 39.90469
[lng] => 116.40717
)
[ad_info] => Array
(
[nation] => 中国
[province] => 北京市
[city] => 北京市
[district] =>
[adcode] => 110000
)
)
)
//curl
function curl_get($url)
{
$headers= array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36');
$oCurl= curl_init();
if (stripos($url,"https://")!== FALSE) {
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($oCurl, CURLOPT_SSLVERSION,1);//CURL_SSLVERSION_TLSv1
}
curl_setopt($oCurl, CURLOPT_TIMEOUT,20);
curl_setopt($oCurl, CURLOPT_URL,$url);
curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER,1);
$sContent= curl_exec($oCurl);
$aStatus= curl_getinfo($oCurl);
curl_close($oCurl);
if (intval($aStatus["http_code"])== 200) {
return $sContent;
}else {
return false;
}
}