首页 > PHP教程 > php开发知识文章

PHP 查询IP详细信息的方法

本文根据当前用户本地IP地址,查询IP地址库,获取IP所在的省市信息,接口为新浪的 int.dpool.sina.com.cn

代码使用了php正则、curl及编码转换相关编程技巧,需要的朋友参考下

代码如下:

class IpGET
{
/**
* 获取IP的归属地( 新浪IP库接口 )
*
* @param $ip String IP地址
* @param $type String 接口返回格式:js,json
* @return Array
*/
public static function getIpCity($ip,$type='json')
{
$link = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=$type&ip=" . $ip . "&t=" . time();
$ipJson = self::httpCurl($link);
preg_match("/\"country\":\"(.*)\"/Uis",$ipJson, $match1);
preg_match("/\"province\":\"(.*)\"/Uis",$ipJson, $match2);
preg_match("/\"city\":\"(.*)\"/Uis",$ipJson, $match3);

return array(
'country' => self::ucode2zh($match1[1]), // 国家
'province' => self::ucode2zh($match2[1]), //
'city' => self::ucode2zh($match3[1]) // 城市
);
}

/**
* Curl函数获取接口信息
*/
public static function httpCurl($url)
{
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_FAILONERROR, 1);
$file_content = curl_exec($curl_handle);
curl_close($curl_handle);
return $file_content;
}

/**
* unicode编码转化为中文,转化失败返回原字符串
*
* @param $code String unicode编码
* @return String
*/
public static function ucode2zh($code)
{
$temp = explode('\u', $code);
$rslt = array();
array_shift($temp);
foreach ($temp as $k => $v) {
$v = hexdec($v);
$rslt[] = '&#' . $v . ';';
}
$r = implode('', $rslt);
return empty($r) ? $code : $r;
}
}

//获取IP地址类使用实例
$ipStr = IpGET::getIpCity('36.32.50.92');
print_r($ipStr);

返回结果

PHP 查询IP详细信息的方法

以上就是根据当前用户本地IP地址,查询IP地址库,获取IP所在的省市信息的全部内容,希望大家能有所收获。

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。