How do I get the external IP of my server using PHP?

后端 未结 12 2648
后悔当初
后悔当初 2020-11-30 07:47

I often hear people say to use \"$_SERVER[\'SERVER_ADDR\']\", but that returns the LAN IP of my server (e.g. 192.168.1.100). I want the external IP.

12条回答
  •  死守一世寂寞
    2020-11-30 08:15

    This is an old thread, but for what it's worth, I'm adding a simple function that I use. It uses outside services (which is inevitable it seems), but it provides a backup service as well, and local caching to avoid repetitive HTTP calls.

    /*
    USAGE
    $ip = this_servers_public_ip(); // Get public IP, and store it locally for subsequent calls.
    $ip = this_servers_public_ip(true); // Force remote query and refresh local cache if exists.
    */
    function this_servers_public_ip($purge=false) {
        $local = sys_get_temp_dir().'/this.servers.public.ip';
        if ( $purge===true && realpath($local) ) {
            unlink($local);
        }
        if ( realpath($local) ) {
            return file_get_contents($local);
        }
        // Primary IP checker query.
        $ip = trim( file_get_contents('https://checkip.amazonaws.com') );
        if ( (filter_var($ip, FILTER_VALIDATE_IP) !== false) ) {
            file_put_contents($local,$ip);
            return $ip;
        }
        // Secondary IP checker query.
        $ip_json = trim( file_get_contents('https://ipinfo.io') );
        $ip_arr = json_decode($ip_json,true);
        $ip=$ip_arr['ip'];
        if ( (filter_var($ip, FILTER_VALIDATE_IP) !== false) ) {
            file_put_contents($local,$ip);
            return $ip;
        }
        return false; // Something went terribly wrong.
    }
    

提交回复
热议问题