0

I'm getting user's IP like this:

// Function to get the client IP address
function get_client_ip() {
    $ipaddress = '';
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';
    return $ipaddress;
}

My code works fine if always one of those header be set. Otherwise what happens when $_SERVER['HTTP_FORWARDED'] = real IP and $_SERVER['HTTP_X_FORWARDED_FOR'] = real ip ? Based on the order of my conditions, $ip will be the fake ip.

So I want to know always one of those will be set or might multiple of them?

Martin AJ
  • 6,261
  • 8
  • 53
  • 111
  • Maybe one, maybe all. Who knows? Depends on the client, the server and everything in between. – rjdown Jul 09 '16 at 02:04
  • @rjdown So my code is wrong? I mean which one is the user's IP? It may be each of them, right? So should I store all of them separately? – Martin AJ Jul 09 '16 at 02:04
  • REMOTE_ADDR is the most reliable, but it's not reliable. I'm sure that didn't help at all, that's how it is though. Store any that are set. – rjdown Jul 09 '16 at 02:07
  • @rjdown `:-)` Overall what's the best approach to get user's IP? – Martin AJ Jul 09 '16 at 02:08
  • Read this http://stackoverflow.com/questions/3003145/how-to-get-the-client-ip-address-in-php and take note of all the warnings...! – rjdown Jul 09 '16 at 02:12

0 Answers0