我需要使用PHP通过代理获取用户的IP地址... 有什么建议吗?
答案 0 :(得分:5)
通常,代理会添加您可以通过服务器变量X-Forwarded-For
$_SERVER['HTTP_X_FORWARDED_FOR']
答案 1 :(得分:1)
这很难做到,并非所有代理都能提供用户的真实IP。我写了这个函数之前尝试找到用户最可能的IP:
function get_ip_address() {
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_CLIENT_IP']))
return $_SERVER['HTTP_CLIENT_IP'];
elseif (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_COMING_FROM']))
return $_SERVER['HTTP_COMING_FROM'];
elseif (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_X_COMING_FROM']))
return $_SERVER['HTTP_X_COMING_FROM'];
elseif (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_FORWARDED']))
return $_SERVER['HTTP_FORWARDED'];
elseif (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_X_FORWARDED']))
return $_SERVER['HTTP_X_FORWARDED'];
elseif (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_FORWARDED_FOR']))
return $_SERVER['HTTP_FORWARDED_FOR'];
elseif (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_X_FORWARDED_FOR']))
return $_SERVER['HTTP_X_FORWARDED_FOR'];
else return $_SERVER['REMOTE_ADDR'];
}
如果您只是在数据库中存储IP,那么该函数只返回1个IP,但我有一个类似的函数,它提供了基于文本的响应,并找到了所有可能的IP。
function get_txt_ip_address() {
$return = '';
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_CLIENT_IP']))
$return .= $_SERVER['HTTP_CLIENT_IP']." (client) / ";
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_COMING_FROM']))
$return .= $_SERVER['HTTP_COMING_FROM']." (cf) / ";
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_X_COMING_FROM']))
$return .= $_SERVER['HTTP_X_COMING_FROM']." (xcf) / ";
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_FORWARDED']))
$return .= $_SERVER['HTTP_FORWARDED']." (fw) / ";
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_X_FORWARDED']))
$return .= $_SERVER['HTTP_X_FORWARDED']." (xfw) / ";
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_FORWARDED_FOR']))
$return .= $_SERVER['HTTP_FORWARDED_FOR']." (fwf) / ";
if (ereg("([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})",$_SERVER['HTTP_X_FORWARDED_FOR']))
$return .= $_SERVER['HTTP_X_FORWARDED_FOR']." (xfwf) / ";
$return .= $_SERVER['REMOTE_ADDR']." (ra) / ";
$return .= gethostbyaddr($_SERVER['REMOTE_ADDR']);
return $return;
}