首页 > php教程 > php手册 > 正文

PHP获取IP信息,php获取ip

WBOY
发布: 2016-06-13 09:12:03
原创
1287 人浏览过

PHP获取IP信息,php获取ip

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

 

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!