Home  >  Article  >  php教程  >  PHP实现获取客户端IP并获取IP信息

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

WBOY
WBOYOriginal
2016-06-06 20:06:30925browse

这篇文章主要介绍了PHP实现获取客户端IP并获取IP信息的方法示例,非常实用,有需要的小伙伴快来参考下吧。

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

代码如下:

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

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

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