欢迎各位大佬批评指正。。谢谢
if (isset($_SERVER)) {
// Use $_SERVER variables by preference
$HTTP_VARS = $_SERVER;
} else if (isset($_ENV)) {
// Fallback to PHP environment variables
$HTTP_VARS = $_ENV;
} else $HTTP_VARS = array();
// Step through the captured $_SERVER or $_ENV array, ignoring the case of the keys.
// (Some "authorities" indicate that the keys can be lower or mixed case!)
$ipAddrList = 'unknown';
foreach($HTTP_VARS as $key => $value) {
$key = strtoupper($key);
$value = str_replace(' ', '', $value);// Get rid of embedded blanks
if ($key == 'HTTP_FORWARDED') {
// We're dealing with the new HTTP Forwarded: by=identifier; for=identifier; host=host; proto=protocol
// See: https://tools.ietf.org/html/rfc7239
$value = str_replace(',for=', ',', strtolower($value)); // Make everything lower-case and then get rid of extraneous "for=" tags
$params = explode(';', $value);// Separate the Forwarded: parameters into an array
foreach ($params as $key => $value) {
if (substr($value,0,4) == 'for=') {
$ipAddrList = substr($value,4);// Everything after "for=" is now a comma-separated list of IPv4 or IPv6 addresses
break;
}
}
break;
}
if ($key == 'HTTP_X_FORWARDED_FOR') {
$ipAddrList = $value;
break;
}
if ($key == 'HTTP_X_FORWARDED') {
$ipAddrList = $value;
break;
}
if ($key == 'HTTP_FORWARDED_FOR') {
$ipAddrList = $value;
break;
}
if ($key == 'HTTP_CLIENT_IP') {
$ipAddrList = $value;
break;
}
if ($key == 'REMOTE_ADDR') {
$ipAddrList = $value;
break;
}
}
$ip = preg_replace('~,.*~', '', $ipAddrList); // Trim everything after the first comma, leaving just the first IPv4 or IPv6 address
$ip = str_replace(array('"', "'"), '', $ip); // Get rid of quotation marks used in some addresses
if (substr($ip,0,1) == '[') {
$ip = preg_replace('~\]:.*~', '', $ip); // Get rid of IPv6 port number that follows closing square bracket
$ip = str_replace(array('[', ']'), '', $ip); // Get rid of square brackets enclosing IPv6 address
} else {
$ip = preg_replace('~:.*~', '', $ip); // Get rid of IPv4 port number that follows last digit of address
}
unset($HTTP_VARS, $key, $value, $params, $ipAddrList); // We don't need this any more
$_SERVER['REMOTE_ADDR'] = $ip;
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.