How to get Public IP address using PHP? [duplicate

2019-09-19 11:59发布

问题:

This question already has an answer here:

  • Get the client IP address using PHP [duplicate] 5 answers

I need to get Public IP address of the system using PHP. I tried the following function:

function get_client_ip() {
    $ipaddress = '';
    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');
    return $ipaddress;
}

But, I got only the localhost IP 127.0.0.1. I am in need of Public IP address. What function is available in PHP to get my Public Ip address which I get from this site:http://www.whatismyip.com/

回答1:

It is not possible to get Your IP address on that way if you run web server on same machine or local LAN where you run your browser client, you will always get local IP address.

If You still want to get Your public address from PHP script, on *nix servers which runs in same network as your browser client, you can get it via command like this:

$myPublicIP = trim(shell_exec("dig +short myip.opendns.com @resolver1.opendns.com"));
echo "My public IP: ".$myPublicIP;


回答2:

Try Using ,

$_SERVER['REMOTE_ADDR']  

Check this link



标签: php ip