首頁 > 後端開發 > php教程 > PHP取得IP訊息

PHP取得IP訊息

WBOY
發布: 2016-08-08 09:28:00
原創
1020 人瀏覽過

<?<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教程有興趣的朋友有所幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板