I have to get the remote url hostname from the server
script
, which one of the following is more reliable:
gethostbyaddr($_SERVER['REMOTE_ADDR'])
or $_SERVER['REMOTE_HOST']
This has nothing to do with reliability. Both variables are just not the same although they may contain the same value under certain circumstances. Let me explain:
$_SERVER['REMOTE_ADDR']
will in all cases contain the IP address of the remote host, where
$_SERVER['REMOTE_HOST']
will contain the DNS hostname, if DNS resolution is enabled (if the HostnameLookups
Apache directive is set to On
, thanks @Pekka). If it is disabled, then $_SERVER['REMOTE_HOST']
will contain the IP address, and this is what you might have observed.
Your code should look like:
$host = $_SERVER['REMOTE_HOST'];
// if both are the same, HostnameLookups seems to be disabled.
if($host === $_SERVER['REMOTE_ADDR']) {
// get the host name per dns call
$host = gethostbyaddr($_SERVER['REMOTE_ADDR'])
}
Note: If you can control the apache directive, I would advice you to turn it off for performance reasons and get the host name - only if you need it - using gethostbyaddr()
$_SERVER['REMOTE_HOST']
will only be set if the HostnameLookups
Apache directive is set to On
.
You could check for $_SERVER['REMOTE_HOST']
first, and if it's not set, do a hostname lookup.
Both are likely to be equally reliable, as they will use the same lookup mechanism internally. For the general reliability of this information, see Reliability of PHP'S $_SERVER['REMOTE_ADDR']
Be aware that hostname lookups can be very slow. Don't do them unless you have a really good reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With