5

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']

sAnS
  • 1,169
  • 1
  • 7
  • 10
Dru
  • 556
  • 4
  • 21

2 Answers2

11

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()

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • thanks for the reply. this way it does the lookup only if neccessary. – Dru May 31 '13 at 09:35
  • you are welcome. :) yes it grabs the host name only if required. Also you should check the note that I've added. – hek2mgl May 31 '13 at 09:37
7

$_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.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088