W3docs

How to Get Remote IP Address in PHP

Sometimes getting the IP address of the client can be tricky. With the help of this snippet, you will manage to get the real remote IP address in PHP.

Getting the real remote IP address of the client can sometimes be quite tricky for PHP programmers.

Receiving the correct remote IP address has a crucial role both for tracking activity and for security purposes.

This tutorial is aimed at helping programmers to overcome such problems. Go ahead and see how to get the real remote IP address in PHP. Often, programmers try to use $_SERVER['REMOTE_ADDR'] for detecting the real IP address of the client:

<?php

function getRemoteIPAddress()
{
  $ip = $_SERVER['REMOTE_ADDR'];
  return $ip;
}

?>

However, don’t get surprised to know that with the code above, you may not receive the real IP address. In case the client uses a proxy server, the function above will not be able to help you to determine the exact IP address of the client. Luckily, there is another solution to the issue.

So, for finding the right IP address, you need to run the following function:

<?php

function getRealIPAddr()
{
  // Check if IP is sent via proxy
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    // X-Forwarded-For may contain multiple IPs; extract and trim the first one
    $ip = trim(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0]);
  } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    // HTTP_CLIENT_IP is rarely used by modern proxies; fallback only
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  } else {
    $ip = $_SERVER['REMOTE_ADDR'];
  }

  return $ip;
}

?>

You can now retrieve the client's IP address by calling the function. For example:

<?php
echo getRealIPAddr();
?>

Note that in production environments, these headers can be spoofed, so proper proxy configuration and header validation are required for security. For production applications, consider using your framework's built-in trusted proxy features (e.g., Symfony's Request::getClientIp()) or validating headers against known proxy IPs.

What is IP Address

The IP address is the abbreviation for the Internet Protocol Address. It is considered a numerical label that is assigned to any device linked to a computer network using the Internet Protocol as a means to communicate.

The two principal functions of the IP address are:

  • Networking or hosting interface identification.
  • Location addressing.

An IP address is specified as a 32-bit number by the Internet Protocol version 4. However, the new IPv6 version applies 128 bits for an IP address. The Internet Assigned Numbers Authority administers the space of the IP addresses. Every ISP administrator should assign an IP address to any device operating with its network.