类似的博客很多,五花八门,来个自己封装的函数,直接上代码,很简单。
1、方案一
只需调用淘宝网 API 接口,即可获取公网或局域网所在的地理位置信息。ip.taobao.com/
/**
* 根据 Ip 获取地址位置
*/
function getIpInfo($internetIp = '')
{
try
{
//内网IP
// A类10.0.0.0~10.255.255.255
// B类172.16.0.0~172.31.255.255
// C类192.168.0.0~192.168.255.255
// ......
$bLocalIp = !filter_var($internetIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
if($bLocalIp)
$internetIp = 'myip';//局域网IP
$requestAPi = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $internetIp;
$opts = array(
'http' => array(
'method' => 'GET',
'timeout' => 1, // 单位秒
)
);
$jsonArr = json_decode( file_get_contents($requestAPi, false, stream_context_create($opts)),
JSON_HEX_TAG | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_HEX_APOS );
// 说明断网
if (!isset($jsonArr) || !isset($jsonArr['code']))
{
return false;
}
// 0 表示成功
if ($jsonArr['code'] !== 0)
{
return false;
}
// 返回的数据结果:
// "ip": "223.98.166.115",
// "country": "中国",
// "area": "",
// "region": "山东",
// "city": "济南",
// "county": "XX",
// "isp": "移动",
// "country_id": "CN",
// "area_id": "",
// "region_id": "370000",
// "city_id": "370100",
// "county_id": "xx",
// "isp_id": "100025"
$data = (array)$jsonArr['data'];
return $data;
}
catch (\Exception $e)
{
}
return false;
}
复制代码
淘宝网 API 接口有限制调用频率
2、方案二
3、获取客户端IP地址
/**
* 获取客户端IP地址
* @param int $type [IP地址类型]
* @param bool $strict [是否以严格模式获取]
* @return mixed [客户端IP地址]
*/
function client_ip($type = 0, $strict = false)
{
$ip = null;
// 0 返回字段型地址(127.0.0.1)
// 1 返回长整形地址(2130706433)
$type = $type ? 1 : 0;
if ($strict) {
/* 防止IP地址伪装的严格模式 */
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown', $arr);
if (false !== $pos) {
unset($arr[$pos]);
}
$ip = trim(current($arr));
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
} else if (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
/* IP地址合法性验证 */
$long = sprintf("%u", ip2long($ip));
$ip = $long ? [$ip, $long] : ['0.0.0.0', 0];
return $ip[$type];
}
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END