Sometimes you have a PHP application and multiple devices, and you need a fast and reliable way to get the hostname of a server. If that is your case, here you will learn the best way to get a hostname with PHP. You can find it if you know the IP address or the local machine is the host.
Gethostbyaddr() PHP function
You can get the hostname if you already have the IP address of it with the gethostbyaddr() PHP function. PHP will perform a reverse DNS lookup for that IP address, and it will show the hostname related to it. This is its syntax:
gethostbyaddr(string $ip): string|false
The result will be either the string of hostname or a false value.
$hostname = gethostbyaddr(“126.96.36.199”);
echo “Hostname is: “. $hostname;
In this case, we are checking the IP address 188.8.131.52, which you can see in the result, belong to the host with hostname – cache.google.com.
There is another very similar function that is the mirror of this one, and it is called the gethostbyname() function. As you could have guessed, you can use it if you have the hostname already, and you need to find the IPv4 address of it.
gethostname() PHP function
The gethostname() PHP function will give you the hostname of the localhost. Its syntax is the following:
It is an inbuilt function in PHP. There are no additional parameters, and the result can be either string with the hostname if successful or false if not.
It works on PHP 5.3 and newer versions.
After this, now you know the best way to get the name of the host using PHP. It is not hard to use it. So go on and try it right away!