PHP实现获取客户端IP并获取IP信息_PHP

WBOY
Release: 2016-06-01 11:06:17
Original
832 people have browsed it

代码很简洁,功能很实用,这里就不多废话了,直接奉上:

代码如下:


/**
 * 获取客户端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();
}

以上就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!