Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 684
Dru Avatar asked Dec 02 '22 23:12

Dru


2 Answers

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

like image 156
hek2mgl Avatar answered Dec 05 '22 12:12

hek2mgl


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

like image 27
Pekka Avatar answered Dec 05 '22 12:12

Pekka