One way is to "ask the public IP" to an external server.
$externalContent = file_get_contents('http://checkip.dyndns.com/');
preg_match('/Current IP Address: \[?([:.0-9a-fA-F]+)\]?/', $externalContent, $m);
$externalIp = $m[1];
I add a script that returns both the detected IP of the client (the browser) and the public IP of the server (local) where the script resides
<?php
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else 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');
else
$ipaddress = 'UNKNOWN';
if (strpos($ipaddress, ",") !== false) :
$ipaddress = strtok($ipaddress, ",");
endif;
return $ipaddress;
}
function get_public_ip(){
$externalContent = file_get_contents('http://checkip.dyndns.com/');
preg_match('/Current IP Address: \[?([:.0-9a-fA-F]+)\]?/', $externalContent, $m);
$externalIp = $m[1];
return $externalIp;
}
$theIP = get_client_ip();
$theExternalIP = get_public_ip();
?>
<p><?php echo 'Detected Client IP : '.$theIP.PHP_EOL;?></p>
<p><?php echo 'Detected (Local) External IP : '.$theExternalIP.PHP_EOL;?></p>