1

I've been using $_SERVER["REMOTE_ADDR"] to obtain the user's IP address for months. Lately, I have noticed that this value may sometimes contain a proxy server IP and not the user's IP, which makes it of little use to me. (I have noticed this issue after I updated to PHP 7.1.0, although I've tried downgrading to the previous PHP version and the results were identical).

I have read tons of SO questions and most of them only address this problem without a solution, or offer the following function as a solution:

function get_ip() {
    $ipaddress = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ipaddress = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ipaddress = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ipaddress = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $ipaddress = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ipaddress = getenv('REMOTE_ADDR');
    else
        $ipaddress = 'UNKNOWN';

    return $ipaddress;
}

This is unreliable too, because these different variables can be spoofed.

Are there any good and reliable solutions to obtain the correct user IP address and not that of any intermediary proxy servers?

John Parker
  • 54,048
  • 11
  • 129
  • 129
Itay Ganor
  • 3,965
  • 3
  • 25
  • 40
  • Why should one be interested in a client IP? I know that is not the question here, sure. I just want to mention this since typically this indicates some form of simple form of authorization scheme which offers a false hope of security... – arkascha Oct 07 '17 at 10:46
  • I use it for simple voting system to make sure people don't vote twice. It's not for something serious, and cookies are not an option for me. – Itay Ganor Oct 07 '17 at 10:51
  • That is totally unreliable! Many systems use dynamic IP addresses. And there are things like proxies. – arkascha Oct 07 '17 at 10:52

1 Answers1

0

Use this function below;

   function checkIPAddress()
   {
      // Get IP Address using $_SERVER['REMOTE_ADDR'];
      $ipaddress = ($_SERVER('REMOTE_ADDR')) ? $_SERVER('REMOTE_ADDR') : '';

       if ( filter_var ($ipaddress, FILTER_VALIDATE_IP) == false)
       {
          //Log bad IP attempt
       }
       else{
          //Received valid IP Address, run next code here.
       }
       
   }

Allow HTTP_X_FORWARDED is a bad habit. Use it when you are doing proxy server, load balancing or when necessary etc.

Community
  • 1
  • 1
Prince Adeyemi
  • 724
  • 6
  • 12