简体   繁体   中英

Accurate client IP in PHP

I want to match my client IP in PHP. I have stored client IP address in the database IP addresss given by http://www.whatismyip.com/ .

while in PHP i used to get client IP Address like this

$client_ip = $_SERVER['REMOTE_ADDR'];

But both IP Addresses giving are different values.

Is there any way to get correct IP address in PHP

$_SERVER['REMOTE_ADDR'] returns the IP address the request originated as seen by the web server. This can be mainly different in the condition when you are accessing the web server from local IP address. Because whatismyip.com returns your public IP and your server will get request from your local IP.

Try to access the page from a remote location and you will get the IP correctly.

If you are developing locally... it's obvious there's gonna be different addresses:

  • external websites will show you the public one
  • internal sites will show you the local one

See Public/Private IP ranges . Do you recognize the local address in the private ranges?

Once you deploy your project online (on a server not in your network) , things will work as expected.

It is better to detect the proxy server forward IP address if exists.

if ($_SERVER['HTTP_X_FORWARD_FOR']) {
  $ip = $_SERVER['HTTP_X_FORWARD_FOR'];
} else {
  $ip = $_SERVER['REMOTE_ADDR'];
}

The PHP codes should be working most of the time now.

function get_ip_address(){
    foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(',', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM