欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

PHP获取IP信息,php获取ip

程序员文章站 2022-03-25 16:31:18
...

PHP获取IP信息,php获取ip

php
/**
 * 获取客户端IP
 * @param  integer $type 返回类型 0:string,1:long
 * @return string|long
 */
function getClientIp($type = 0) {
    $ip = NULL;
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip  = trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}
/**
 * 获取IP信息
 * @param  string|long $ip  IP地址
 * @return array
 */
function getIpInfo($ip)
{
    if (is_long($ip)) {
        $ip = long2ip($ip);
    }
    $api = 'http://ip.taobao.com/service/getIpInfo.php';
    $ret = file_get_contents($api . '?ip=' . $ip);
    $ret = json_decode($ret, true);
    if ($ret['code'] == 0) {
        return $ret['data'];
    } 
    return array();
}
相关标签: ip地址