如何在PHP中获取用户的IP地址?

重复:

07000

编辑:服务器是通过suPHP运行PHP5的Debian linux盒子.以上帖子已被阅读.此代码涵盖了所提到的所有要点,但仍返回未知地址.

我的代码总是要求知道远程IP地址.一旦我们获得了访问的IP地址,我们是否拿起代理地址并不重要.

下面的函数是我们目前使用的,但是在超过20%的套件中,服务器属于未知情况并且在$_SERVER var中没有任何内容.

function getip()
{
    if ( $_SERVER["HTTP_CLIENT_IP"] && strcasecmp($_SERVER["HTTP_CLIENT_IP"], "unknown") )
    {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    else if ( $_SERVER["HTTP_X_FORWARDED_FOR"] && strcasecmp($_SERVER["HTTP_X_FORWARDED_FOR"], "unknown") )
    {
        $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
    {
        $ip = getenv("REMOTE_ADDR");
    }
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
    {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    else
    {
        $ip = "unknown: ".var_dump($_SERVER, true);
    }
    return($ip);
}
Some random blog found via google有趣的代码实际上是在评论中而不是博客提到的内容.

function getIpAddress() 
{
    return (empty($_SERVER['HTTP_CLIENT_IP'])?(empty($_SERVER['HTTP_X_FORWARDED_FOR'])?
    $_SERVER['REMOTE_ADDR']:$_SERVER['HTTP_X_FORWARDED_FOR']):$_SERVER['HTTP_CLIENT_IP']);
}




function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
https://stackoverflow.com/questions/848091/how-can-i-get-the-users-ip-address-in-php

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何在PHP中获取用户的IP地址?