php根据ip获取地址信息

本文介绍了一个使用PHP通过调用淘宝IP地址库API来获取指定IP地址地理位置信息的方法。该脚本利用curl发起POST请求,并解析返回的JSON数据,最终输出IP地址对应的国家、地区、省份及城市信息。
<?php 

$url = 'http://ip.taobao.com/service/getIpInfo2.php';//淘宝提供的一个ip地址库

$data=array('ip'=>'219.144.202.12');

function curl_post($url, $header=array(), $data=array(), $referer=NULL, $timeout=5){

    if (!$header) {

      $header[] = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

      $header[] = "Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7";

      $header[] = "Accept-Encoding: gzip,deflate";

      $header[] = "User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; zh-CN; rv:1.9.2) Gecko/20100115 Firefox/3.6";

    }



    $ch = curl_init();

    curl_setopt($ch, CURLOPT_POST, 1);

    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_ENCODING, '');

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    if ($referer) curl_setopt($ch, CURLOPT_REFERER, $referer);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $r = curl_exec($ch);

    curl_close($ch);

    return $r;



}

$html= curl_post($url,null,$data,'http://ip.taobao.com/ipSearch.php');

$json = json_decode($html);



echo $json->data->country.$json->data->area.$json->data->region.$json->data->city;

 

转载于:https://my.oschina.net/u/234439/blog/784659

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值