PHP获取IP信息

WBOY
WBOYoriginal
2016-08-08 09:28:001025parcourir

<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获取IP信息,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn