php通过淘宝API查询IP地址归属等信息

Class TaobaoIPQuery2{
  private static $_requestURL = 'http://ip.taobao.com/service/getIpInfo.php';
  public static function getIPInfo($ip){
    $long = ip2long($ip);
    if($long === 0){
      throw new Exception('IP address error', 5);
    }
    $ip=long2ip($long);
    $IPInfo = self::queryIPInfo($ip);
    return self::parseJSON($IPInfo);
  }
   
  private static function queryIPInfo($ip){
    $query = http_build_query(array('ip'=>$ip));
    $ch = curl_init();
    $options = array(
      CURLOPT_URL => sprintf('%s?%s', self::$_requestURL, $query),
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_AUTOREFERER => false,
      CURLOPT_FOLLOWLOCATION => false,
      CURLOPT_HEADER => false,
      CURLOPT_TIMEOUT => 3.0,
    );
    curl_setopt_array($ch, $options);
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
  }
   
  private static function parseJSON($json){
    $O = json_decode ($json, true);
    if(false === is_null($O)){
      return $O;
    }
    if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
      $errorCode = json_last_error();
      if(isset(self::$_JSONParseError[$errorCode])){
        throw new Exception(self::$_JSONParseError[$errorCode], 5);
      }
    }
    throw new Exception('JSON parse error', 5);
  }
  private static $_JSONParseError = array(
    JSON_ERROR_NONE=>'No error has occurred',  
    JSON_ERROR_DEPTH=>'The maximum stack depth has been exceeded',  
    JSON_ERROR_CTRL_CHAR=>'Control character error, possibly incorrectly encoded',  
    JSON_ERROR_STATE_MISMATCH=>'Invalid or malformed JSON',  
    JSON_ERROR_SYNTAX=>'Syntax error',  
    JSON_ERROR_UTF8=>'Malformed UTF-8 characters, possibly incorrectly encoded',
  );
}

 

$ip = $_SERVER["REMOTE_ADDR"];
$ipquery = new taobaoIPQuery($ip);
$region = $ipquery->get_region();
$country = $ipquery->get_country();
$city = $ipquery->get_city();

 

 

转载于:https://my.oschina.net/u/1168113/blog/1546340

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值