Home > php教程 > php手册 > PHP获取IP地址输出为数组程序代码

PHP获取IP地址输出为数组程序代码

WBOY
Release: 2016-05-25 16:44:34
Original
1150 people have browsed it

在php中获取IP地址的方法有很多种,下面我介绍利用linux命令获取IP地址然后转换成数组输出,下面也介绍了一些常用关于php ip地址处理实例.

PHP获取服务器IP地址,用PHP执行ifconfig获得Linux服务器IP并输出为数组,下面是代码:

<?php
function getServerIp() { //用ifconfig读取服务器IP并输出为数组
    $ss = exec(&#39;/sbin/ifconfig | sed -n &#39;s / ^ * . *addr:
        ([0 - 9.] {
            7,
        }) . *$ / 1 / p&#39;&#39;, $arr);
        return $arr;
    }
    $ips = getServerIp();
    foreach ($ips as $k => $v) { //过滤IP
        if (substr($v, 0, 3) == &#39;127&#39; || substr($v, 0, 3) == &#39;10.&#39; || substr($v, 0, 7) == &#39;192.168&#39; || substr($v, 0, 6) == &#39;172.16&#39;) {
            unset($ips[$k]);
        }
    }
    shuffle($ips); //重新排序
    print_r($ips);
?>
Copy after login

一些php获取ip地址例,代码如下:

<?php
    function GetIP() {
        if (!emptyempty($_SERVER["HTTP_CLIENT_IP"])) {
            $cip = $_SERVER["HTTP_CLIENT_IP"];
        } elseif (!emptyempty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif (!emptyempty($_SERVER["REMOTE_ADDR"])) {
            $cip = $_SERVER["REMOTE_ADDR"];
        } else {
            $cip = "无法获取!";
        }
        return $cip;
    }
    echo GetIP();
?> 	
Copy after login

我这里有一个比较公用的方法来获取用户ip地址,代码如下:

<?php
    function get_user_ip() {
        if (isset($_SERVER[&#39;HTTP_CLIENT_IP&#39;]) && $_SERVER[&#39;HTTP_CLIENT_IP&#39;] != &#39;unknown&#39;) {
            $ip = $_SERVER[&#39;HTTP_CLIENT_IP&#39;];
        } elseif (isset($_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;]) && $_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;] != &#39;unknown&#39;) {
            $ip = $_SERVER[&#39;HTTP_X_FORWARDED_FOR&#39;];
        } else {
            $ip = $_SERVER[&#39;REMOTE_ADDR&#39;];
        }
        return $ip;
    }
?>
Copy after login

PHP获取IP所在地区(调用新浪API获取IP所在地),代码如下:

<?php
    function get_location($ip) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" . $ip);
        $location = curl_exec($curl);
        $location = json_decode($location);
        if ($location === FALSE) return "";
        return emptyempty($location->desc) ? $location->province . $location->city . $location->district . $location->isp : $location->desc;
    }
?>
Copy after login

               
               

永久链接:

转载随意!带上文章地址吧。

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template