<p>php 获取本机外网/公网IP<br />
<br />
大家一般都是用$_SERVER['REMOTE_ADDR']来获取用户IP,<br />
</p>
<p>但是如果使用了反向代理的,HTTP头中REMOTE_ADDR就不是用户的地址,反而是上一级代理的地址了。</p>
<p>经过我的研究有两种方法来获取用户的真实外网IP。<br />
</p>
<p>方法一:curl</p>
<p><br />
function get_onlineip() {<br />
$ch = curl_init('http://www.ip138.com/ip2city.asp');<br />
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);<br />
$a = curl_exec($ch);<br />
preg_match('/[(.*)]/', $a, $ip);<br />
return $ip[1];<br />
}</p>
<p><br />
</p>
<p>方法二:$_SERVER['HTTP_X_FORWARDED_FOR']来获取相应的地址</p>
<p><br />
function get_onlineip() {<br />
$onlineip = '';<br />
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {<br />
$onlineip = getenv('HTTP_CLIENT_IP');<br />
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {<br />
$onlineip = getenv('HTTP_X_FORWARDED_FOR');<br />
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {<br />
$onlineip = getenv('REMOTE_ADDR');<br />
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {<br />
$onlineip = $_SERVER['REMOTE_ADDR'];<br />
}<br />
return $onlineip;<br />
}</p>