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.
Learn more about Reverse DNS (rDNS)
This is its syntax:
gethostbyaddr(string $ip): string|false
The result will be either the string of hostname or a false value.
Example code:
<?php
$hostname = gethostbyaddr(“64.15.113.39”);
echo “Hostname is: “. $hostname;
?>
In this case, we are checking the IP address 64.15.113.39, 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:
gethostname(): string|false
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.
Example code:
<?php
echo gethostname();
?>
Get IPv4 address with PHP explained
Conclusion
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!