如何使用PHP获取客户端IP地址?

我想通过他/她的IP地址登录到我的网站的用户的记录。


当前回答

互联网背后有不同类型的用户,因此我们希望从不同的部分捕获IP地址。这些都是:

1. $ _SERVER [' REMOTE_ADDR '] - 其中包含客户端的真实IP地址。这是您可以从用户那里找到的最可靠的值。

2. $ _SERVER [' REMOTE_HOST '] - 这将获取用户正在查看当前页面的主机名。但是要使这个脚本工作,必须在httpd.conf中配置主机名查找。

3.$ _SERVER [' HTTP_CLIENT_IP '] - 当用户来自共享Internet服务时,这将获取IP地址。

4. $_SERVER['HTTP_X_FORWARDED_FOR'] -这将从用户获取IP地址时,他/她是后面的代理。

所以我们可以用下面这个组合函数从不同位置观看的用户那里得到真实的IP地址,

// Function to get the user IP address
function getUserIP() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

其他回答

echo $_SERVER['REMOTE_ADDR'];

http://php.net/manual/en/reserved.variables.server.php

$_SERVER['REMOTE_ADDR']可能不包含真实的客户端IP地址,例如,它会为通过代理连接的客户端提供一个代理地址。这可能 不过,这是你真正想要的,取决于你如何处理ip。某人的私有RFC1918地址可能对你没有任何好处,如果你试图查看你的流量来自哪里,或者记住用户最后从哪个IP连接,代理或NAT网关的公共IP可能更适合存储。

有几个HTTP报头,如X-Forwarded-For,可以由各种代理设置,也可以不设置。问题是这些只是HTTP头,任何人都可以设置。他们的内容没有保证。$_SERVER['REMOTE_ADDR']是web服务器接收到连接的实际物理IP地址,响应将被发送到该地址。其他任何信息都是随意和自愿的。只有一种情况下您可以信任此信息:您正在控制设置此报头的代理。意思只有当你知道100%的头是在哪里和如何设置,你应该注意它的任何重要的。

话虽如此,下面是一些示例代码:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

编者注:使用上述代码具有安全隐患。客户端可以设置所有的HTTP报头信息(例如。$_SERVER['HTTP_…])到它想要的任意值。因此,使用$_SERVER['REMOTE_ADDR']更可靠,因为这不能由用户设置。

来自:http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html

我最喜欢的解决方案是Zend Framework 2使用的方式。它还考虑$_SERVER属性HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP, REMOTE_ADDR,但是它声明了一个类来设置一些可信代理,并且它返回一个IP地址而不是一个数组。我认为这是最接近它的解决方案:

class RemoteAddress
{
    /**
     * Whether to use proxy addresses or not.
     *
     * As default this setting is disabled - IP address is mostly needed to increase
     * security. HTTP_* are not reliable since can easily be spoofed. It can be enabled
     * just for more flexibility, but if user uses proxy to connect to trusted services
     * it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR'].
     *
     * @var bool
     */
    protected $useProxy = false;

    /**
     * List of trusted proxy IP addresses
     *
     * @var array
     */
    protected $trustedProxies = array();

    /**
     * HTTP header to introspect for proxies
     *
     * @var string
     */
    protected $proxyHeader = 'HTTP_X_FORWARDED_FOR';

    // [...]

    /**
     * Returns client IP address.
     *
     * @return string IP address.
     */
    public function getIpAddress()
    {
        $ip = $this->getIpAddressFromProxy();
        if ($ip) {
            return $ip;
        }

        // direct IP address
        if (isset($_SERVER['REMOTE_ADDR'])) {
            return $_SERVER['REMOTE_ADDR'];
        }

        return '';
    }

    /**
     * Attempt to get the IP address for a proxied client
     *
     * @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2
     * @return false|string
     */
    protected function getIpAddressFromProxy()
    {
        if (!$this->useProxy
            || (isset($_SERVER['REMOTE_ADDR']) && !in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies))
        ) {
            return false;
        }

        $header = $this->proxyHeader;
        if (!isset($_SERVER[$header]) || empty($_SERVER[$header])) {
            return false;
        }

        // Extract IPs
        $ips = explode(',', $_SERVER[$header]);
        // trim, so we can compare against trusted proxies properly
        $ips = array_map('trim', $ips);
        // remove trusted proxy IPs
        $ips = array_diff($ips, $this->trustedProxies);

        // Any left?
        if (empty($ips)) {
            return false;
        }

        // Since we've removed any known, trusted proxy servers, the right-most
        // address represents the first IP we do not know about -- i.e., we do
        // not know if it is a proxy server, or a client. As such, we treat it
        // as the originating IP.
        // @see http://en.wikipedia.org/wiki/X-Forwarded-For
        $ip = array_pop($ips);
        return $ip;
    }

    // [...]
}

在这里查看完整代码: https://raw.githubusercontent.com/zendframework/zend-http/master/src/PhpEnvironment/RemoteAddress.php

互联网背后有不同类型的用户,因此我们希望从不同的部分捕获IP地址。这些都是:

1. $ _SERVER [' REMOTE_ADDR '] - 其中包含客户端的真实IP地址。这是您可以从用户那里找到的最可靠的值。

2. $ _SERVER [' REMOTE_HOST '] - 这将获取用户正在查看当前页面的主机名。但是要使这个脚本工作,必须在httpd.conf中配置主机名查找。

3.$ _SERVER [' HTTP_CLIENT_IP '] - 当用户来自共享Internet服务时,这将获取IP地址。

4. $_SERVER['HTTP_X_FORWARDED_FOR'] -这将从用户获取IP地址时,他/她是后面的代理。

所以我们可以用下面这个组合函数从不同位置观看的用户那里得到真实的IP地址,

// Function to get the user IP address
function getUserIP() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

这个函数应该能正常工作

function Get_User_Ip()
{
    $IP = false;
    if (getenv('HTTP_CLIENT_IP'))
    {
        $IP = getenv('HTTP_CLIENT_IP');
    }
    else if(getenv('HTTP_X_FORWARDED_FOR'))
    {
        $IP = getenv('HTTP_X_FORWARDED_FOR');
    }
    else if(getenv('HTTP_X_FORWARDED'))
    {
        $IP = getenv('HTTP_X_FORWARDED');
    }
    else if(getenv('HTTP_FORWARDED_FOR'))
    {
        $IP = getenv('HTTP_FORWARDED_FOR');
    }
    else if(getenv('HTTP_FORWARDED'))
    {
        $IP = getenv('HTTP_FORWARDED');
    }
    else if(getenv('REMOTE_ADDR'))
    {
        $IP = getenv('REMOTE_ADDR');
    }

    //If HTTP_X_FORWARDED_FOR == server ip
    if((($IP) && ($IP == getenv('SERVER_ADDR')) && (getenv('REMOTE_ADDR')) || (!filter_var($IP, FILTER_VALIDATE_IP))))
    {
        $IP = getenv('REMOTE_ADDR');
    }

    if($IP)
    {
        if(!filter_var($IP, FILTER_VALIDATE_IP))
        {
            $IP = false;
        }
    }
    else
    {
        $IP = false;
    }
    return $IP;
}