Best way to get hostname with PHP

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:


$hostname = gethostbyaddr(“”);

echo “Hostname is: “. $hostname;


In this case, we are checking the IP address, which you can see in the result, belong to the host with hostname –

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:


echo gethostname();


Get IPv4 address with PHP explained


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!

Leave a Reply

Your email address will not be published. Required fields are marked *