1

I've found two approaches to gives me user's IP:

Approach1 :

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

Aproach2 :

function get_ip() {
    if ($_SERVER['HTTP_X_FORWARDED_FOR']) {
        ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

May you please tell me which one is better? Actually I need to execute that function get_ip() per each page loading. Also as you see, the first approach has a lot of conditions (if-statements). So Can I simply use the second one?

In other word, is there advantage from approach1 than approach2?

stack
  • 10,280
  • 19
  • 65
  • 117
  • 1
    Possible duplicate of [getenv() vs. $\_ENV in PHP](http://stackoverflow.com/questions/8798294/getenv-vs-env-in-php) – mister martin Jun 23 '16 at 14:14
  • @mistermartin The difference between those two approaches isn't only using `getenv()` and `$_SERVER`. – stack Jun 23 '16 at 14:16

1 Answers1

4

It is safer to use first one because you do more checks. Most of the time you can find the ip in REMOTE_ADDR or HTTP_X_FORWARDED_FOR if it's going throw proxy, but sometimes you can have in other variables because there is no standard for this.

Personally I usually go with second approach because it's more clean, but if you want to make sure you have the ip use the first one.

Also you don't need to use getenv(). You can check directly in $_SERVER

Check this answer also: What is the difference between HTTP_CLIENT_IP and HTTP_X_FORWARDED_FOR?

Community
  • 1
  • 1
Daniel Dudas
  • 2,972
  • 3
  • 27
  • 39
  • You are right .. But actually I have a bad feeling about having a lot of conditions on the way of each page load. So I really don't know should I choose which one. – stack Jun 23 '16 at 14:18
  • You don't have to worry about 5 extra `if` statement. – Daniel Dudas Jun 23 '16 at 14:21
  • I wouldn't worry at all about performance with those conditionals. Logging the IP is far more resource hungry. – Progrock Jun 23 '16 at 14:21
  • I really shouldn't care about 5 `if` statements? I think that's a nightmare .. 5 conditions take a lot of process and I think it makes the performance weak. Thank you anyway .. upvote – stack Jun 23 '16 at 14:27