How to get the client IP in PHP?

Asked

Viewed 3,044 times

2

I have researched several forums and even here but none of the solutions I saw brought me the right result. On all attempts I receive as ip ::1

Follow the code I’m using

<?php

  if (!empty($_SERVER['HTTP_CLIENT_IP']))   
    {
      $ip_address = $_SERVER['HTTP_CLIENT_IP'];
    }
  elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
    {
      $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
  else
    {
      $ip_address = $_SERVER['REMOTE_ADDR'];
    }
  echo $ip_address;
?>
  • @Stormwind No solution available

  • 1

    @RORSCHACH, has no solution accepted, but if you see the first answer, it already responds to what the user wants (more specifically in the 3rd line).

1 answer

0

Try this code:

<?PHP

function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}


$user_ip = getUserIP();

echo $user_ip; // Output IP address [Ex: 177.87.193.134]


?>

Don’t forget to nay access your page by the link https://localhost , instead, access the link www.nomedoseusite.com if you are staying or by your IP:

https://192.168.0.1 //Seu número de IP

Browser other questions tagged

You are not signed in. Login or sign up in order to post.