Heim  >  Artikel  >  php教程  >  PHP获取IP信息,php获取ip

PHP获取IP信息,php获取ip

WBOY
WBOYOriginal
2016-06-13 09:12:031286Durchsuche

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>

 

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn