Best way to get IP address?

What is the best method to get the users IP address? I’ve seen a couple of codes on the Internet to get the users IP address, like these:

$ipaddress = $_SERVER["REMOTE_ADDR"];
$ipaddress = getenv('REMOTE_ADDR');
$ipaddress = @$REMOTE_ADDR;

and even this


function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

That is the one I use, but to my knowledge there is no way to guarantee the IP you get. I wouldn’t rely on it.

You should never ever use anything other then “$_SERVER[“REMOTE_ADDR”]” alright. That function “getRealIpAddr” DO NOT USE THAT! The only time you shoulde use “HTTP_CLIENT_IP” or “HTTP_X_FORWARDED_FOR” is when you are behind a known proxy or load balancer. Under any other condition you must use “$_SERVER[“REMOTE_ADDR”]” only.

Repeat: If your server is not behind a proxy or load balancer, only ever use “$_SERVER[“REMOTE_ADDR”]”

HTTP_CLIENTT_IP, HTTP_X_FORWARDED_FOR, are both user defined and can contain garbage data.