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

时间:2013-05-15 11:40:13

标签: php remote-client

我有一个PHP网页,我试图获取客户端IP,但我得到的是服务器GATEWAY IP地址(192.168.0.1)。

这就是我在办公室所拥有的:

ISP ---> ISP路由器--->我的路由器(192.168.0.1)----> (192.168.0.2)我的服务器。

我尝试了所有这些线路,但我无法获得真正的IP,只有SERVER GATEWAY ip。

$_SERVER['HTTP_X_FORWARDED_FOR']
$_SERVER['HTTP_CLIENT_IP']
$_SERVER['HTTP_X_REAL_IP']
$_SERVER['GATEWAY_INTERFACE']
$_SERVER['SERVER_ADDR']
$_SERVER['SERVER_NAME']
$_SERVER['SERVER_SOFTWARE']
$_SERVER['SERVER_PROTOCOL']
$_SERVER['REQUEST_METHOD']
$_SERVER['REQUEST_TIME']
$_SERVER['QUERY_STRING']
$_SERVER['DOCUMENT_ROOT']
$_SERVER['HTTP_ACCEPT']
$_SERVER['HTTP_ACCEPT_CHARSET']
$_SERVER['HTTP_ACCEPT_ENCODING']
$_SERVER['HTTP_ACCEPT_LANGUAGE']
$_SERVER['HTTP_CONNECTION']
$_SERVER['HTTP_HOST']
$_SERVER['HTTP_REFERER']
$_SERVER['HTTP_USER_AGENT']
$_SERVER['HTTPS']
$_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_HOST']
$_SERVER['REMOTE_PORT']
$_SERVER['SCRIPT_FILENAME']
$_SERVER['SERVER_ADMIN']
$_SERVER['SERVER_PORT'] 
$_SERVER['SERVER_SIGNATURE']
$_SERVER['PATH_TRANSLATED']
$_SERVER['SCRIPT_NAME']
$_SERVER['REQUEST_URI']
$_SERVER['PHP_AUTH_DIGEST']
$_SERVER['PHP_AUTH_USER'] 
$_SERVER['PHP_AUTH_PW']
$_SERVER['AUTH_TYPE']

以下变量是“未定义的”:

-HTTP_X_FORWARDED_FOR
-HTTP_CLIENT_IP
-HTTP_X_REAL_IP
-HTTPS
-REMOTE_HOST
-PATH_TRANSLATED
-PHP_AUTH_DIGEST
-PHP_AUTH_USER
-PHP_AUTH_PW
-AUTH_TYPE



编辑:尝试“var_dump($ _ SERVER)”并找不到客户端IP地址:(

编辑2:我谷歌搜索了一下,我“找到了答案”。用户Martin Hohenberg所说的是对的。在NAT进程中,Headers被破坏,因此我的服务器无法读取原始IP地址。目前,我不知道这个问题的可行解决方案,而无需将服务器移到前面。

2 个答案:

答案 0 :(得分:3)

Similar question

尝试

echo $_SERVER['REMOTE_ADDR'];

Read more

function getUserIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) //if from shared
    {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //if from a proxy
    {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        return $_SERVER['REMOTE_ADDR'];
    }
}

请查看阅读更多链接和问题链接

答案 1 :(得分:2)

如果您是从运行服务器的计算机发出请求,那么$_SERVER['REMOTE_ADDR']显然会包含您自己的IP地址,即192.168.0.1