是否有更简洁的方法来格式化我创建的函数以获取TeamSpeak上的某些内容的客户端IP地址?
function getClientIp() {
if (!empty($_SERVER['HTTP_CLIENT_IP']))
return $_SERVER['HTTP_CLIENT_IP'];
else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
return $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(!empty($_SERVER['HTTP_X_FORWARDED']))
return $_SERVER['HTTP_X_FORWARDED'];
else if(!empty($_SERVER['HTTP_FORWARDED_FOR']))
return $_SERVER['HTTP_FORWARDED_FOR'];
else if(!empty($_SERVER['HTTP_FORWARDED']))
return $_SERVER['HTTP_FORWARDED'];
else if(!empty($_SERVER['REMOTE_ADDR']))
return $_SERVER['REMOTE_ADDR'];
else
return false;
}
初学者的一点
答案 0 :(得分:1)
这与您的代码执行的操作相同,但它更简洁,您可以向数组添加标头,而不是扩展if / else。
function getClientIp() {
$headers = ['HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','
HTTP_FORWARDED_FOR','HTTP_FORWARDED','REMOTE_ADDR'];
foreach ($headers as $h) {
if (!empty($_SERVER[$h])) {
return $_SERVER[$h];
}
}
return false;
}
答案 1 :(得分:0)
function getClientIp() {
return !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] :
!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] :
!empty($_SERVER['HTTP_X_FORWARDED']) ? $_SERVER['HTTP_X_FORWARDED']:
!empty($_SERVER['HTTP_FORWARDED_FOR']) ? $_SERVER['HTTP_FORWARDED_FOR']:
!empty($_SERVER['HTTP_FORWARDED']) ? $_SERVER['HTTP_FORWARDED']:
!empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
}