本文介绍了如何在PHP中获取用户的IP地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器是一个通过suPHP运行PHP5的Debian linux系统.上面的帖子已经阅读.这段代码涵盖了所有提到的要点,但仍然返回未知地址.

Server is a Debian linux box running PHP5 through suPHP. Above post has been read. This code covers all points mentioned but still returns unknown addresses.

我的代码始终要求知道远程IP地址.一旦可以获取访问的IP地址,是否选择代理地址就没关系了.

My code always requires that the remote IP address be known. It doesn't matter if we pick up the proxy address once we can get some IP address for the access.

下面的功能是我们当前使用的功能,但是在超过20%的工具包中,服务器会遇到未知情况,并且$ _SERVER变量中没有任何内容.

Function below is what we current use however in over 20% of kits, the server falls through to the unknown case and has nothing in the $_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);
}

推荐答案

通过google找到了一些随机博客.有趣的代码实际上是在注释中,而不是博客所提到的.

Some random blog found via google . The interesting code is actually in the comment rather than what the blogger has mentioned.

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;
}

这篇关于如何在PHP中获取用户的IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:30