Home >php教程 >PHP源码 >通过api获取访问的ip来源

通过api获取访问的ip来源

PHP中文网
PHP中文网Original
2016-05-26 08:19:371724browse

使用新浪或者阿里的地址库

<?php
/**
 * ip search
 * Created by PhpStorm.
 * User: saint
 * Date: 14-10-23
 * Time: 下午4:28
 */
 
class ip_lib
{
    // 淘宝ip地址库
    public function get_ip_info_taobao($ip)
    {
        $server_api = &#39;http://ip.taobao.com/service/getIpInfo.php?ip=&#39;;
        $uri = $server_api . $ip;
 
        $json_string = $this->get_remote_data($uri);
 
        $array = json_decode($json_string, true);
        $ret = array();
        if($array[&#39;code&#39;])
        {
            $ret = array(
                &#39;country&#39; => &#39;未知&#39;,
                &#39;city&#39; => &#39;未知&#39;,
                &#39;isp&#39; => &#39;未知&#39;
            );
        }
        else
        {
            $ret[&#39;country&#39;] = $array[&#39;data&#39;][&#39;country&#39;] ? $array[&#39;data&#39;][&#39;country&#39;] : &#39;未知&#39;;
            $ret[&#39;city&#39;] = $array[&#39;data&#39;][&#39;city&#39;] ? $array[&#39;data&#39;][&#39;city&#39;] : &#39;未知&#39;;
            $ret[&#39;isp&#39;] = $array[&#39;data&#39;][&#39;isp&#39;] ? $array[&#39;data&#39;][&#39;isp&#39;] : &#39;未知&#39;;
        }
 
        return $ret;
    }
 
    // 新浪ip地址库
    public function get_ip_info_sina($ip)
    {
        $server_api = &#39;http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=&#39;;
        $uri = $server_api . $ip;
 
        $json_string = $this->get_remote_data($uri);
 
        $array = json_decode($json_string, true);
        $ret = array();
        if($array[&#39;ret&#39;] != 1)
        {
            $ret = array(
                &#39;country&#39; => &#39;未知&#39;,
                &#39;city&#39; => &#39;未知&#39;,
                &#39;isp&#39; => &#39;未知&#39;
            );
        }
        else
        {
            $ret[&#39;country&#39;] = $array[&#39;country&#39;] ? $array[&#39;country&#39;] : &#39;未知&#39;;
            $ret[&#39;city&#39;] = $array[&#39;province&#39;] ? $array[&#39;province&#39;] : &#39;未知&#39;;
            $ret[&#39;isp&#39;] = $array[&#39;city&#39;] ? $array[&#39;city&#39;] : &#39;未知&#39;;
        }
 
        return $ret;
    }
 
    private function get_remote_data($uri)
    {
        $ch = curl_init($uri) ;
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
        return $output = curl_exec($ch) ;
    }
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn