大家好, 如何使用PHP获取我的用户的广域网IP地址....
大家好, 如何使用PHP获取我的用户的广域网IP地址....
file_get_contents("http://bot.whatismyipaddress.com");
将很容易地获取IP,无需进行任何后处理。
$_SERVER['REMOTE_ADDR']可以给你HTTP请求所在的IP地址。如果你说的“用户”是指浏览你的网站的人,那么这很可能就是你要找的。
如果你想要获取“执行用户”的WAN IP,你可以使用以下代码行来获取你的服务器的WAN IP:
$wanIP=file_get_contents("http://www.whatismyip.com/automation/n09230945.asp");
请注意,这将会向whatismyip.com进行DNS和HTTP连接,这将会拖慢你的网站。
我使用whatismyip.com来获取IP地址。虽然我不会在生产环境中使用它,但我会在集成测试中使用它(特别是Paypal IPN无法在本地主机上工作,并且需要通过WAN IP设置端口转发)。
(请注意他们的使用政策!http://www.whatismyip.com/faq/automation.asp)
function getWANIP() {
$url = "http://automation.whatismyip.com/n09230945.asp";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_ENCODING, "UTF-8");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//UNCOMMENT TO DEBUG TO output.tmp
//curl_setopt($ch, CURLOPT_VERBOSE, true); // Display communication with server
//$fp = fopen("output.tmp", "w");
//curl_setopt($ch, CURLOPT_STDERR, $fp); // Display communication with server
$response = curl_exec($ch);
curl_close($ch);
if ( $response === FALSE ) {
throw new Exception("Error while retrieving server data: " . curl_error($ch));
}
return $response;
}