Dru
Dru

Reputation: 556

Which is more reliable gethostbyaddr($_SERVER['REMOTE_ADDR']) or $_SERVER['REMOTE_HOST']

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

Upvotes: 5

Views: 6455

Answers (2)

hek2mgl
hek2mgl

Reputation: 158080

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

Upvotes: 11

Pekka
Pekka

Reputation: 449603

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

Upvotes: 8

Related Questions