What's the most reliable method of obtaining the user's IP address?

144 views Asked by At

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?

1

There are 1 answers

0
Prince Adeyemi On

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.