Do you know how to get an IPv4 address with PHP from a host? No. Now It is your time to learn it and start using it in your code. It is very simple, don’t worry.
$_SERVER and REMOTE_ADDR
We can get the IP address of the user with $_SERVER in PHP. The information about the user and its activities could help us for security or marketing purposes.
The most basic way to collect this information in PHP is with REMOTE_ADDR. The answer will be the IP address of the user that is currently on the webpage.
Example code:
<?php
echo ‘User IP Address – ‘.$_SERVER[‘REMOTE_ADDR’];
?>
You might have a problem if the user uses a proxy. In such a case, you can try the following and get the real IP address of the user:
<?php
function getIPAddress() {
//whether ip is from the share internet
if(!emptyempty($_SERVER[‘HTTP_CLIENT_IP’])) {
$ip = $_SERVER[‘HTTP_CLIENT_IP’];
}
//whether ip is from the proxy
elseif (!emptyempty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) {
$ip = $_SERVER[‘HTTP_X_FORWARDED_FOR’];
}
//whether ip is from the remote address
else{
$ip = $_SERVER[‘REMOTE_ADDR’];
}
return $ip;
}
$ip = getIPAddress();
echo ‘User Real IP Address – ‘.$ip;
?>
If you use the PHP code above, you will get the real IP address of the user, no matter if he or she is behind a proxy.
Gethostbyname() PHP function
If you want to know the IP address of a host, and you already know its hostname, you can easily use the gethostbyname() function.
PHP will perform a forward DNS lookup for that hostname, and it will show the IPv4 address related to it. This is its syntax:
gethostbyname(string $hostname): string|false
The result will be either the string of the IP address or a false value.
Example code:
<?php
$ip_address = gethostbyname(“google.com”);
echo “IP Address is: “. $ip_address;
?>
In this case, the hostname is google.com, and the IP address that we got is 173.194.41.67.
gethostbynamel() PHP function
Similar to the previous function with the difference, it will show a complete list of IP addresses of the host.
<?php
$ip_address_array = gethostbynamel(“google.com“);
print_r($ip_address_array);
?>
Suggested article: How to check DNS records using PHP?
Conclusion
Now you know how to get the IPv4 address of a host with PHP. You can also do the opposite and get the hostname of a host if you know its IPv4 address with gethostbyaddr(). It could be a good idea to check it out, too, so you have a better and richer knowledge of PHP.