PHP利用经纬度精确拦截某个区域的访问
利用百度提供的ip定位可以得到访问者的一个大概的地理位置一般可以精确到某个区,在返回的json可以得到访问者的地理位置,如果你需要禁止某个地区的访客可以根据json的地理位置关键词区做一个匹配,这样是比较简单精确地做法,但是简单的东西显得没技术含量所以需要装一下B,利用json的经纬度去画圆匹配范围,在这个圆里面就返回True否则就返回Fale!具体代码如下:
<?php
function GetIpAdd(){
if (getenv("HTTP_CLIENT_IP")){
$ip = getenv("HTTP_CLIENT_IP");
}elseif(getenv("HTTP_X_FORWARDED_FOR")){
$ip = getenv("HTTP_X_FORWARDED_FOR");
}elseif(getenv("REMOTE_ADDR")){
$ip = getenv("REMOTE_ADDR");
} else {
$ip = 0;
}
// echo $ip;
return $ip;
}
function curlget($url){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
class Convert{
private $PI = 3.14159265358979324;
private $x_pi = 0;
public function __construct()
{
$this->x_pi = 3.14159265358979324 * 3000.0 / 180.0;
}
/**
* 判断一个坐标是否在圆内
* 思路:判断此点的经纬度到圆心的距离 然后和半径做比较
* 如果此点刚好在圆上 则返回true
* @param $point ['lng'=>'','lat'=>''] array指定点的坐标
* @param $circle array ['center'=>['lng'=>'','lat'=>''],'radius'=>''] 中心点和半径
*/
function is_point_in_circle($point, $circle){
$distance = $this -> distance($point['lat'],$point['lng'],$circle['center']['lat'],$circle['center']['lng']);
if($distance <= $circle['radius']){
return true;
}else{
return false;
}
}
/**
* 计算两个点之间的距离
* @param $latA 第一个点的纬度
* @param $lonA 第一个点的经度
* @param $latB 第二个点的纬度
* @param $lonB 第二个点的经度
* @return float
*/
function distance($latA, $lonA, $latB, $lonB)
{
$earthR = 6371000.;
$x = cos($latA * $this->PI / 180.) * cos($latB * $this->PI / 180.) * cos(($lonA - $lonB) * $this->PI / 180);
$y = sin($latA * $this->PI / 180.) * sin($latB * $this->PI / 180.);
$s = $x + $y;
if ($s > 1) $s = 1;
if ($s < -1) $s = -1;
$alpha = acos($s);
$distance = $alpha * $earthR;
return $distance;
}}
function getwz($ip){
$key="********************";//百度地图秘钥
$url="https://api.map.baidu.com/location/ip?ak=".$key."&coor=bd09ll&ip=".$ip;
$data= curlget($url);
return $data;
}
$json_str= getwz(GetIpAdd());
$obj=json_decode($json_str);
$lat=$obj->content->point->y;
$lng=$obj->content->point->x;
// print_r( $lng.",".$lat);
$point = ['lng'=>$lng,'lat'=>$lat];
//中心位置和范围
$circle = [
'center'=>['lng'=>104.074292,'lat'=>30.558627],
'radius'=>500.83038795571
];
//百度地图坐标拾取工具http://api.map.baidu.com/lbsapi/getpoint/index.html
$convert = new Convert();
$bool = $convert -> is_point_in_circle($point,$circle);
if($bool){echo "在范围内";}else{echo "不在范围内";}扫描二维码推送至手机访问。
本サイト上に掲載の文章、画像、写真などを無断で複製することは法律で禁じられています。全ての著作権はGAMESHに帰属します。


