How to Get 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 the 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:

Watch a course Learn object oriented PHP

<?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 ip from share internet
  if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
  }
  //to check ip is pass from proxy
  elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  } else {
    $ip = $_SERVER['REMOTE_ADDR'];
  }

  return $ip;
}

?>

Finally, it’s done, and you can be sure to have the exact IP address of the client.

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 the 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 bites 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.