is it well-written?
Well, not really... it is very redundant. A commonly accepted principle is the Don't Repeat Yourself. principle. For example, the following block:
if (getenv('HTTP_CLIENT_IP'))
$mainIp = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$mainIp = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$mainIp = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$mainIp = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$mainIp = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$mainIp = getenv('REMOTE_ADDR');
else
$mainIp = 'UNKNOWN';
return $mainIp;
Could be simplified by putting each key into an array:
$ipKeys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', ...];
or that could be stored in a constant:
const IP_KEYS = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', ...];
Then iterate over those keys to set the value once a value is found:
foreach ($ipKeys as $key) {
if (getenv($key)) {
return getenv($key);
}
}
return 'UNKNOWN';
As Gwyn Evans suggests the return value of the call to getenv()
can be stored in a variable and if that value doesn't evaluate to false
then the variable can be returned, though this may go against an accepted coding standard/style guide so use with caution:
foreach ($ipKeys as $key) {
if ($value = getenv($key)) {
return $value;
}
}
return 'UNKNOWN';