How to Get the Client IP Address in PHP
Often it is needed to collect clients’ IP addresses for security purposes or for tracking the site activity. Here, we will show you how to do it in PHP.
Frequently, it is necessary to gather clients’ IP addresses for tracking activity or security purposes.
Using the $_SERVER Variable
The <kbd class="highlighted">$_SERVER</kbd> variable provides a simple and efficient way to retrieve a user's IP address. It is an array that contains server and environment-related information in PHP.
Let’s begin with the simplest approach: accessing <kbd class="highlighted">$_SERVER['REMOTE_ADDR']</kbd>. It returns the IP address of the connecting user:
Retrieve Client IP via REMOTE_ADDR
<?php
echo 'User IP - ' . $_SERVER['REMOTE_ADDR'];
?>However, $_SERVER['REMOTE_ADDR'] may return an incorrect address if the user is behind a proxy or load balancer. To handle this, you can check additional headers and validate the result:
Handle Proxies and Load Balancers
<?php
function getUserIpAddr()
{
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// IP passed through proxy (may contain multiple IPs)
$ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
} elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
// IP from shared internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : 'Unknown';
}
echo 'User Real IP - ' . getUserIpAddr();
?>Note: HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP headers can be spoofed. In production, always validate these against a trusted proxy list or use a dedicated library.
Getting IP Addresses of the Website
You can also resolve the IP address of any domain using the <kbd class="highlighted">gethostbyname()</kbd> function:
Resolve Domain to IP Address
<?php
$ip_address = gethostbyname("www.google.com");
echo "IP Address of Google is - " . $ip_address;
echo "<br>";
$ip_address = gethostbyname("www.javatpoint.com");
echo "IP Address of javaTpoint is - " . $ip_address;
?>Note: This function resolves DNS records, so the returned IP may differ from the actual server IP if the site uses a CDN or load balancer. Additionally, gethostbyname() is deprecated as of PHP 8.2; consider using dns_get_record() for modern compatibility.