本地localhost、127.0.0.1时,均能获取外网IP地址。
<?php
//获取外网IP的地址,以下两个均测试成功
//$url = 'http://tool.huixiang360.com/zhanzhang/ipaddress.php';
$url = 'http://city.ip138.com/ip2city.asp';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch);
preg_match('/\[(.*)\]/', $a, $ip);
//echo $ip[1];
//根据IP地址定位所在城市
①使用淘宝IP库
$res = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=$ip");
$res = json_decode($res,true);
print_r($res);
?>
返回结果如图:
②使用新浪IP库
$res = @file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip");
$res = json_decode($res,true);
print_r($res);
?>
返回结果如图: